tags:

views:

154

answers:

1

What happen internally when we call BeginInvoke on a variable of delegate type?

+2  A: 

This depends on the type of object in which you call BeginInvoke.

ISynchronizeInvoke is the interface that defines BeginInvoke. It passes the delegate to the object that implements that interface, and that object will (should) schedule the thread to run on it's own main thread.

There are a few objects that implement this interface. The Dispatcher in WPF does this - when you call BeginInvoke on the dispatcher, the delegate is added to the dispatcher's queue, and run when it is appropriate.

The Control base class in Windows Forms also implements ISynchronizeInvoke (and I believe this may be what your question was hinting at). In Windows Forms, things are much more complicated. Here is a great article explaining the details. Basically, what happens when you call BeginInvoke on a winforms control is that a special marshaller creates a windows message that is passed to the program, and the UI thread queues the delegate to be run. It's a bit more complex than that (as that article describes), but that's the basic idea. The delegate is then run on the main UI thread.

There are other objects that implement ISynchronizeInvoke, but most of them are objects that are managing and running their own thread. These objects maintain a queue of delegates, and add yours to that queue so it runs on their thread.

Reed Copsey