Pri*_*ank 6 c# graphics multithreading bitmap
我正在编写一个应用程序来捕获使用该CopyFromScreen方法的屏幕,并且还想保存我捕获的图像以通过我的本地网络发送.所以,我正在尝试将捕获的屏幕存储在一个位图上,并在两个线程上保存另一个位图,即先前捕获的屏幕.
然而,这是抛出一个InvalidOperationException,说对象目前在其他地方使用.System.Drawing.dll抛出异常.
我尝试过锁定,并使用单独的位图来保存和捕获屏幕.我如何阻止这种情况发生?相关代码:
Bitmap ScreenCapture(Rectangle rctBounds)
{
Bitmap resultImage = new Bitmap(rctBounds.Width, rctBounds.Height);
using (Graphics grImage = Graphics.FromImage(resultImage))
{
try
{
grImage.CopyFromScreen(rctBounds.Location, Point.Empty, rctBounds.Size);
}
catch (System.InvalidOperationException)
{
return null;
}
}
return resultImage;
}
void ImageEncode(Bitmap bmpSharedImage)
{
// other encoding tasks
pictureBox1.Image = bmpSharedImage;
try
{
Bitmap temp = (Bitmap)bmpSharedImage.Clone();
temp.Save("peace.jpeg");
}
catch (System.InvalidOperationException)
{
return;
}
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Interval = 30;
timer1.Start();
}
Bitmap newImage = null;
private async void timer1_Tick(object sender, EventArgs e)
{
//take new screenshot while encoding the old screenshot
Task tskCaptureTask = Task.Run(() =>
{
newImage = ScreenCapture(_rctDisplayBounds);
});
Task tskEncodeTask = Task.Run(() =>
{
try
{
ImageEncode((Bitmap)_bmpThreadSharedImage.Clone());
}
catch (InvalidOperationException err)
{
System.Diagnostics.Debug.Write(err.Source);
}
});
await Task.WhenAll(tskCaptureTask, tskEncodeTask);
_bmpThreadSharedImage = newImage;
}
Run Code Online (Sandbox Code Playgroud)
我通过创建一个带有单个按钮的简单 winforms 项目,简单地重现了您的问题。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Task.Run(() => SomeTask());
}
public void SomeTask() //this will result in 'Invalid operation exception.'
{
var myhandle = System.Drawing.Graphics.FromHwnd(Handle);
myhandle.DrawLine(new Pen(Color.Red), 0, 0, 100, 100);
}
}
Run Code Online (Sandbox Code Playgroud)
为了解决这个问题,您需要执行以下操作:
public partial class Form1 : Form
{
private Thread myUIthred;
public Form1()
{
myUIthred = Thread.CurrentThread;
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Task.Run(() => SomeTask());
}
public void SomeTask() // Works Great.
{
if (Thread.CurrentThread != myUIthred) //Tell the UI thread to invoke me if its not him who is running me.
{
BeginInvoke(new Action(SomeTask));
return;
}
var myhandle = System.Drawing.Graphics.FromHwnd(Handle);
myhandle.DrawLine(new Pen(Color.Red), 0, 0, 100, 100);
}
}
Run Code Online (Sandbox Code Playgroud)
该问题(正如 Spektre 所暗示的那样)是尝试从非 UI 线程调用 UI 方法的结果。“BeginInvoke”实际上是“this.BeginInvoke”,“this”是由 UI 线程创建的表单,因此一切正常。