【发布时间】:2017-07-27 09:25:33
【问题描述】:
我正在编写一个应用程序来使用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;
}
【问题讨论】:
-
它究竟在哪里确定正在使用的东西?
-
我假设它是
_bmpThreadSharedImage,您没有包含在上面的代码中导致问题? -
@BugFinder 异常未处理消息出现在 Program.cs 中的
Application.Run(new Form1())行,CopyFromScreen和Bitmap.Save方法被突出显示 -
克隆图像,然后运行任务..(注意您不需要重新克隆它)
-
@BugFinder 那是立即抛出同样的异常
标签: c# multithreading graphics bitmap