跨线程操作无效...-VB.NET [英] Crossthread operation not valid... - VB.NET
问题描述
我正在使用vb.net,在我的程序中,运行后台工作程序时出现此跨线程操作无效"错误,这将使此文本框启用为true.我的主子程序将首先将启用状态设置为false,然后在后台工作程序运行时将其重新设置为true,然后退出.为什么会给我一个错误?仅供参考:与此相关的代码更多,但我不想使其变得更加混乱...
I am using vb.net, and in my program I get this 'crossthread operation not valid' error when I run my backgroundworker that will make this textbox enabled true. My main sub will first turn the enabled to false, and when the backgroundworker runs it will turn it back true then exit. Why does it give me an error? FYI: There is more code to this but I don't want to make it any more confusing...
这是堆栈跟踪:
at System.Windows.Forms.Control.get_Handle()
at System.Windows.Forms.Control.OnEnabledChanged(EventArgs e)
at System.Windows.Forms.Control.set_Enabled(Boolean value)
at Helium.Form1.BackgroundWorker1_DoWork(Object sender, DoWorkEventArgs e) in C:\Users\Kevin\documents\visual studio 2010\Projects\Helium\Helium\Form1.vb:line 167
at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e)
at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)
这是确切的错误消息:
{"Cross-thread operation not valid: Control 'mainText' accessed from a thread other than the thread it was created on."}
有人可以帮帮我吗!
谢谢
KEvin
推荐答案
BackgroundWorker
类的目的是在GUI保持响应的同时在 non-GUI 线程上执行工作.除非您将Control.CheckForIllegalCrossThreadCalls
设置为false
(不应该这样做),或者按照其他答案中的建议使用Invoke
(我也不建议这样做),否则您将获得非法的线程操作异常.
The purpose of the BackgroundWorker
class is to perform work on a non-GUI thread while the GUI remains responsive. Unless you set Control.CheckForIllegalCrossThreadCalls
to false
(which you shouldn't do), or use Invoke
as suggested in the other answers (which I also wouldn't recommend), you're going to get an illegal cross-thread operation exception.
如果您希望在BackgroundWorker
运行时 发生与GUI相关的东西",通常建议使用BackgroundWorker.ReportProgress
方法并将适当的处理程序附加到BackgroundWorker.ProgressChanged
事件.如果您希望BackgroundWorker
完成后在GUI上发生某些事情,则只需附加处理程序即可将GUI更新为BackgroundWorker.RunWorkerCompleted
事件.
If you want GUI-related "stuff" to happen while your BackgroundWorker
is running, I'd generally recommend using the BackgroundWorker.ReportProgress
method and attaching an appropriate handler to the BackgroundWorker.ProgressChanged
event. If you want something on the GUI to happen once the BackgroundWorker
is finished, then simply attach your handler to update the GUI to the BackgroundWorker.RunWorkerCompleted
event.
这篇关于跨线程操作无效...-VB.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!