views:

63

answers:

2

Control.Invoke executes the specified delegate on the thread that owns the control's underlying window handle.

For years I have just accepted that this is the way it has to be, but I have never understood why.

The only thing I can think of is that the code is terribly thread unsafe, and instead of just adding a little synchronization in the control code, the framework just dissallows it and forces us down this route - throwing the baby out with the bath water!

  • Is it sheer Microsoft laziness, or is there something Im just not getting?

  • Do other programming frameworks / other OSes have similar problems or is it just a Windows thing?

  • Is there any way around it other than changing every function in our app?

A: 

There's an in-depth review about marshaling execution on the UI thread.

Darin Dimitrov
+4  A: 

This is a limitation of the underlying Windows user interface and has little to do with the .NET framework itself. Performing many actions on controls and windows (in the Windows sense, not the component model sense) requires that the actions be performed on the thread that created the window handle. The .NET framework is like any other application and must abide by this rule.

Certainly, Microsoft could have put syncronization in the framework to prevent this problem, but doing so would have added a great deal of performance overhead for applications that do not need that functionality (because they're largely single threaded).

Microsoft's decision is to force those that need the overhead to manage it explicitly rather than forcing it on everyone.

Mystere Man
Ok, I understand not wanting to have extra performance overhead, but wouldnt it be a similar overhead for the framework to call Control.Invoke itself rather than raise the “Cross-thread operation not valid: Control ‘name here’ accessed from a thread other than the thread it was created on” exception?
Mongus Pong
Calling Control.Invoke has certain responsibilites that the framework cannot simply assume an application knows about. For example, if you are not careful you can create deadlock situations, and if the framework just did this for you, it could be creating deadlocks without your knowledge. Here's a good example http://social.msdn.microsoft.com/forums/en-US/clr/thread/a35e5298-33c4-4461-b956-bf265484219e
Mystere Man
Ok, yes I understand that. Thanks, that clears up my confusion somewhat!
Mongus Pong
By the way, you may be interested in using the SyncronizationContext, which is a new class Microsoft created to help address this issue. See this codeproject article: http://www.codeproject.com/KB/threads/SynchronizationContext.aspx
Mystere Man