跨线程操作无效... - VB.NET [英] Crossthread operation not valid... - VB.NET

查看:28
本文介绍了跨线程操作无效... - VB.NET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 vb.net,在我的程序中,当我运行我的后台工作程序时,我收到了这个跨线程操作无效"错误,这将使该文本框启用为真.我的主要子程序将首先将启用变为假,当后台工作程序运行时,它将返回真然后退出.为什么它给我一个错误?仅供参考:这里有更多代码,但我不想让它变得更加混乱......

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:UsersKevindocumentsvisual studio 2010ProjectsHeliumHeliumForm1.vb:line 167
   at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e)
   at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)

这里是确切的错误信息:

and here is the exact error message:

{"Cross-thread operation not valid: Control 'mainText' accessed from a thread other than the thread it was created on."}

谁能帮帮我!

谢谢,

凯文

推荐答案

BackgroundWorker 类的目的是在 非 GUI 线程上执行工作,而 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆