Reputation: 4864
It is well-known that you cannot update the UI from any other thread other than the UI thread.
However, I just discovered some code, that gets a value of a listview virtualsize, from a non-UI thread without Exception.
So really my question is: what interaction can you have with the UI from a non-UI thread?
Thank you Theo
Upvotes: 2
Views: 543
Reputation: 942256
The specific rule is that you cannot call a Windows API function that uses the Handle of a window. 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. The MSDN docs lists only 4 of them as always safe to use: InvokeRequired, Invoke(), BeginInvoke() and CreateGraphics().
But yes, sometimes a property value is available and doesn't require an API call. The Text property is a good example. It is cached because it is used so often. Reading the Text property doesn't generate an exception, you just get cached value. But writing the Text property goes kaboom, updating the text on the screen requires an API call. ListView.VirtualSize works the exact same way.
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. You'll get a stale value, a classic threading problem known as a race condition.
Upvotes: 5
Reputation: 29640
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. That means that when the UI thread updates the data while you are retrieving it, you do get corrupt data.
Upvotes: 6