Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reason for .NET UI element thread-restriction

We know that it is not possible to execute code that manipulates the properties of any UI element from any thread other than the thread the element was instantiated on... My question is: Why?

I remember that when we used COM user interface elements, (in COM/Visual Basic 6.0 days), that all UI elements were created using COM classes and co-classes that stored their resources using a memory model referred to as Thread-Local-Storage (TLS), but as I recall, this was required because of something related to the way COM components were constructed, and should not be relevant to .NET UI elements. What's the underlying reason why this restriction still exists?

Is it because the underlying Operating System still uses COM-based Win32 API classes for all UI elements, even the ones manipulated in a managed .NET application?

like image 494
Charles Bretana Avatar asked Jun 01 '10 23:06

Charles Bretana


1 Answers

AFAIK, it's more basic than even COM. It goes right down to the good ol' Windows API. I believe that windows in Windows are expected to be owned by a thread, period. Each thread has its own message pump, dispatching messages to the windows it owns. It's a pretty fundamental construct of Windows -- maybe a bit archaic these days, but fundamental.

My sense of it is that this thread affinity helps for interoperability when you need to integrate WPF into Windows Forms applications, or if you need to monkey with a Windows object somewhere else in your application using a HWND that you got somewhere... It probably also is what allows older versions of Windows (XP) to host WPF applications without any major architectural changes to the OS itself.

like image 109
Dave Markle Avatar answered Oct 21 '22 02:10

Dave Markle