在WinForms中,为什么不能从其他线程更新UI控件? [英] In WinForms, why can't you update UI controls from other threads?

查看:65
本文介绍了在WinForms中,为什么不能从其他线程更新UI控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确定有充分的理由(或至少是体面的理由).什么事?

I'm sure there is a good (or at least decent) reason for this. What is it?

推荐答案

因为您很容易陷入僵局(还有其他问题).

Because you can easily end up with a deadlock (among other issues).

例如,您的辅助线程可能正在尝试更新UI控件,但是UI控件将等待由辅助线程锁定的资源被释放,因此两个线程最终都互相等待.正如其他人所评论的那样,这种情况并非UI代码独有,而是特别常见.

For exmaple, your secondary thread could be trying to update the UI control, but the UI control will be waiting for a resource locked by the secondary thread to be released, so both threads end up waiting for each other to finish. As others have commented this situation is not unique to UI code, but is particularly common.

在其他语言(例如C ++)中,您可以随意尝试执行此操作(不会像WinForms中那样引发异常),但是如果发生死锁,您的应用程序可能会冻结并停止响应.

In other languages such as C++ you are free to try and do this (without an exception being thrown as in WinForms), but your application may freeze and stop responding should a deadlock occur.

顺便说一句,您可以轻松地告诉UI线程您要更新控件,只需创建一个委托,然后在该控件上调用(异步)BeginInvoke方法即可将其传递给您的委托.例如

Incidentally, you can easily tell the UI thread that you want to update a control, just create a delegate, then call the (asynchronous) BeginInvoke method on that control passing it your delegate. E.g.

myControl.BeginInvoke(myControl.UpdateFunction);

这等效于从工作线程执行C ++/MFC PostMessage

This is the equivalent to doing a C++/MFC PostMessage from a worker thread

这篇关于在WinForms中,为什么不能从其他线程更新UI控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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