简体   繁体   English

非UI线程,UI访问

[英]Non-UI thread, UI access

It is well-known that you cannot update the UI from any other thread other than the UI thread. 众所周知,您无法从UI线程以外的任何其他线程更新UI。

However, I just discovered some code, that gets a value of a listview virtualsize, from a non-UI thread without Exception. 但是,我刚刚发现了一些代码,该代码从没有Exception的非UI线程获取listview virtualsize的值。

So really my question is: what interaction can you have with the UI from a non-UI thread? 所以,实际上我的问题是:您可以通过非UI线程与UI进行哪些交互?

Thank you Theo 谢谢西奥

Because it works without throwing an exception, does not mean you should do this. 因为它在工作时不会引发异常,但这并不意味着您应该这样做。

The problem is that besides the Invoke requirement for methods that update the UI, these controls also do not support multi threading. 问题在于,除了对更新UI的方法的Invoke要求外,这些控件还不支持多线程。 That means that when the UI thread updates the data while you are retrieving it, you do get corrupt data. 这意味着当UI线程在检索数据时更新数据时,确实会损坏数据。

The specific rule is that you cannot call a Windows API function that uses the Handle of a window. 特定规则是您不能调用使用窗口句柄的Windows API函数。 It isn't exactly obvious whether or not using a property or calling a method of a control will end up making such an API call. 使用属性或调用控件的方法是否最终会进行这样的API调用并不清楚。 The MSDN docs lists only 4 of them as always safe to use: InvokeRequired, Invoke(), BeginInvoke() and CreateGraphics(). MSDN文档仅列出其中四个始终可以安全使用:InvokeRequired,Invoke(),BeginInvoke()和CreateGraphics()。

But yes, sometimes a property value is available and doesn't require an API call. 但是是的,有时属性值可用,不需要API调用。 The Text property is a good example. Text属性是一个很好的例子。 It is cached because it is used so often. 缓存它是因为它经常使用。 Reading the Text property doesn't generate an exception, you just get cached value. 读取 Text属性不会产生异常,您只会得到缓存的值。 But writing the Text property goes kaboom, updating the text on the screen requires an API call. 但是编写 Text属性会变得很麻烦,更新屏幕上的文本需要API调用。 ListView.VirtualSize works the exact same way. ListView.VirtualSize的工作原理完全相同。

You don't get the exception but it is still not kosher. 您没有得到例外,但它仍然不是犹太洁食。 After all, the UI thread might change the Text property as well, a microsecond later. 毕竟,一毫秒后,UI线程也可能会更改Text属性。 You'll get a stale value, a classic threading problem known as a race condition. 您将获得一个过时的值,这是一个经典的线程问题,称为竞争条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM