views:

206

answers:

4

What does that method do exactly? I was thinking that it maybe went out into a separate thread, but handled things like control updating on the correct thread. But now I am starting to think that it maybe just runs on the UI thread. Which means that calling BeginInvoke on a control from the UI is pretty much the same as calling Invoke? Or?

A: 

I'm not 100% sure I get that last sentence.

It contains "from the UI...", does that mean "you call BeginInvoke from the same thread the UI is living on?" or "on a control from the UI", that is, a control which is part of the UI?

Anyway, both methods ends up running the delegate in question on the same thread the UI lives on. The difference is of course that Invoke blocks, and BeginInvoke doesn't. The blocking relates to the thread that does the calling.

Lasse V. Karlsen
+5  A: 

It basically adds the delegate to a queue of "tasks to execute". The UI thread runs those tasks in order.

The difference between Control.Invoke and Control.BeginInvoke is basically that Control.Invoke block the worker thread until the task has executed on the UI thread, whereas BeginInvoke doesn't. I'm not sure offhand whether there's any difference between BeginInvoke and Invoke when you call it from the UI thread.

Jon Skeet
So basically BeginInvoke is nice to use from threads that are not the UI thread, so it doesn't have to wait for the UI to update itself?
Svish
Exactly - but only when you really *don't* need to wait for the UI to update :)
Jon Skeet
Exactly. But that made sense! Thanks :)
Svish
A: 

Control.BeginInvoke is generally used to update the UI/Control on the thread that created the UI. UI elements have a design constraint that they can only be updated from the creating thread.

Hence to update the UI from a different (worker / threadpool) thread, you have to switch to the right thread. Control.BeginInvoke does that for you - asynchronously (in that you dont block till the delegate is executed). Invoke does the same thing except that you block till the delegate has been executed.

1st google result - WinForms UI Thread Invokes: An In-Depth Review of Invoke/BeginInvoke/InvokeRequred

Gishu
A: 

Note that if you use Control.BeginInvoke to invoke a delegate that returns something, you can then use Control.EndInvoke to access the returned value. If the delegate hasn't executed yet, EndInvoke will block until it has returned.

Travis Heseman