簡體   English   中英

我正在使用backgroundworker並得到:InvalidOperationException:跨線程操作無效-我應該如何處理?

[英]I'm using backgroundworker and getting: InvalidOperationException: Cross-thread operation not valid - how should I handle it?

考慮:

private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
    Bitmap newbmp = new Bitmap(512, 512);
    IEnumerable<Point> CommonList = null;
    StreamWriter w = new StreamWriter(@"c:\diff\diff.txt");
    pixelscoordinatesinrectangle = new List<Point>();
    pixelscoordinatesinrectangle = pointsAffected.ToList();
    DrawIt = false;
    for (int i = 0; i < trackBar1FileInfo.Length; i++)
    {
        DrawIt = true;
        this.BeginInvoke(new MethodInvoker(delegate
        {
            trackBar1.Value = i;

                    LoadPictureAt(trackBar1.Value, sender);
                    pictureBox1.Load(trackBar1FileInfo[i].FullName);

            ConvertedBmp = ConvertTo24(trackBar1FileInfo[trackBar1.Value].FullName);
            ConvertedBmp.Save(ConvertedBmpDir + "\\ConvertedBmp.bmp");
            mymem = ToStream(ConvertedBmp, ImageFormat.Bmp);
        }));
        Button1Code();
        pictureBox1.Refresh();
        newpixelscoordinates = new List<Point>();
        newpixelscoordinates = pointsAffected.ToList();
        CommonList = pixelscoordinatesinrectangle.Intersect(newpixelscoordinates);
        foreach (Point s in CommonList)
        {
            w.WriteLine("The following points are the same" + s);
            newbmp.SetPixel(s.X, s.Y, Color.Red);
        }
    }
    w.Close();
    using (Graphics G = Graphics.FromImage(newbmp))
    {
        G.DrawRectangle(pen, rect);
    }
    newbmp.Save(@"c:\newbmp\newbmp.bmp", ImageFormat.Bmp);
    newbmp.Dispose();
}

異常消息:

跨線程操作無效:從創建該線程的線程以外的線程訪問控件“ pictureBox1”。

我試圖使用this.BeginInvoke(new MethodInvoker(delegate

即使現在在BeginInvoke之后使用代碼時,它也會顯示異常,因此我也需要在其他代碼上使用BeginInvoke。

使用BeginInvoke是個好方法嗎? 還是我應該以其他方式解決它,如果可以,怎么辦?

在Windows GUI編程中:

  1. 將耗時的任務移到單獨的線程中以保持UI響應,您選擇使用BackgroundWorker,這是一個不錯的選擇。
  2. 您無法從后台線程訪問UI元素( Cross-thread operation not valid異常),這就是為什么您需要調用BeginInvoke來訪問Picturebox的原因。

記住, BeginInvoke調用的代碼實際上是在UI線程上運行的。 因此,如果將所有代碼都放入BeginInvoke的DoWork中 ,則與不使用Backgroundworker相同-實際上,情況甚至更糟,因為創建新線程並編組對UI線程的調用會產生很大的性能開銷。

因此,您僅應在必要時調用BeginInvoke當代碼需要訪問UI元素時,其余代碼不應包裝在BeginInvoke

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM