[英]I'm using backgroundworker and getting: InvalidOperationException: Cross-thread operation not valid - how should I handle it?
Consider: 考虑:
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();
}
Exception message: 异常消息:
Cross-thread operation not valid: Control 'pictureBox1' accessed from a thread other than the thread it was created on.
跨线程操作无效:从创建该线程的线程以外的线程访问控件“ pictureBox1”。
I tried to use this.BeginInvoke(new MethodInvoker(delegate
我试图使用
this.BeginInvoke(new MethodInvoker(delegate
Even now when using the code after the BeginInvoke, it is showing the exception so I need to use the BeginInvoke on the other code too. 即使现在在BeginInvoke之后使用代码时,它也会显示异常,因此我也需要在其他代码上使用BeginInvoke。
Is using BeginInvoke a good way? 使用BeginInvoke是个好方法吗? Or I should solve it in other way and if so how?
还是我应该以其他方式解决它,如果可以,怎么办?
In Windows GUI programming: 在Windows GUI编程中:
Cross-thread operation not valid
exception), that is why you need to call BeginInvoke
to access the Picturebox. Cross-thread operation not valid
异常),这就是为什么您需要调用BeginInvoke
来访问Picturebox的原因。 Remember the code called by BeginInvoke
is actually running on UI thread. 记住,
BeginInvoke
调用的代码实际上是在UI线程上运行的。 So if you put all the code in the DoWork in BeginInvoke , it is the same as not using Backgroundworker
- actually it is even worse, because creating a new thread and marshaling the call to UI thread have significant performance overhead. 因此,如果将所有代码都放入BeginInvoke的DoWork中 ,则与不使用
Backgroundworker
相同-实际上,情况甚至更糟,因为创建新线程并编组对UI线程的调用会产生很大的性能开销。
So you should call BeginInvoke
only when it is necessary - when the code needs to access UI elements, the rest code should not be wrapped inside BeginInvoke
. 因此,您仅应在必要时调用
BeginInvoke
当代码需要访问UI元素时,其余代码不应包装在BeginInvoke
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.