c# - 保存位图并使用 graphics.copyFromScreen parallel-y 时出现 InvalidOperationException

标签 c# multithreading graphics 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;
}

img1 img2

最佳答案

我通过创建一个带有单个按钮的简单 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);
    }
}

为了解决这个问题,您需要执行以下操作:

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);
    }

}

问题是(正如 Spektre 暗示的那样)是尝试从非 UI 线程调用 UI 方法的结果。 “BeginInvoke”实际上是“this.BeginInvoke”,“this”是由 UI 线程创建的表单,因此一切正常。

关于c# - 保存位图并使用 graphics.copyFromScreen parallel-y 时出现 InvalidOperationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45346585/

相关文章:

c# - 在 C# 中将二维数组转换为一维数组?

c# - NancyFx 配置请求容器

c# - 无法发送到 SignalR 组

python - 使用 Flask Web 应用程序监控实时数据流

c# - 在指定时间段后停止方法

delphi - 如果未调用 TPngImage.Free(),则当 TPngImage 超出范围时,是否调用 TPngImage.Destroy()

c# - 使用 SQL Server 中的存储过程动态更新

Java:在此示例中防止死锁

c - OpenGL 段错误

multithreading - 使用 Haskell Graphics.Gloss 时出现 GLUT fatal error