为什么我不需要非 GUI 线程调用某些表单元素?
我有一个在非 GUI 线程上调用函数的 BackgroundWorker
。我注意到,对于某些表单元素,我可以在不执行调用的情况下更新 GUI。其他的仍然会导致运行时错误,因为程序试图以非线程安全的方式更新 GUI。
这是为什么?
I have a BackgroundWorker
that calls a function on a non-GUI thread. I've noticed that for some form elements I can get away with updating the GUI without doing the invoke. Others will still result in a runtime error because the program attempted to update the GUI in a non-threadsafe way.
Why is that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能偶然发现了一些不检查上下文并引发异常的方法或属性。这并不意味着这样做是个好主意。事实上,我会不惜一切代价避免它。
更新:
假设这里使用 WinForms。
如果你觉得调用太麻烦,可以使用扩展方法:
然后,在BackgroundWorker的DoWork中:
我发现这个比BackgroundWorkers ReportProgress好用很多。
You've probably stumbled upon some methods or properties that don't check context and throw an exception. That doesn't mean it is a good idea to do so. Infact, I would avoid it at any cost.
Update:
Assuming WinForms here.
If you think it is too cumbersome to invoke, use an extension method:
Then, in DoWork of BackgroundWorker:
I find this a lot easier to use than BackgroundWorkers ReportProgress.
并非所有 gui 元素及其方法都被转换为 WM_something。有一些方法可以直接工作,根本不使用消息队列。因此,它们可以在任何线程中安全地使用。
Not all gui elements and their methods are translated to WM_something. There are methods that work directly not using message queue at all. Therefore, they are safe to use from any thread.