Just wondering what the difference between BeginInvoke() and Invoke() are?
Mainly what each one would be used for.
EDIT: What is the difference between creating a threading object and calling invoke on that and just calling BeginInvoke() on a delegate? or are they the same thing?
Do you mean
Delegate.Invoke/BeginInvokeorControl.Invoke/BeginInvoke?Delegate.Invoke: Executes synchronously, on the same thread.Delegate.BeginInvoke: Executes asynchronously, on athreadpoolthread.Control.Invoke: Executes on the UI thread, but calling thread waits for completion before continuing.Control.BeginInvoke: Executes on the UI thread, and calling thread doesn’t wait for completion.Tim’s answer mentions when you might want to use
BeginInvoke– although it was mostly geared towardsDelegate.BeginInvoke, I suspect.For Windows Forms apps, I would suggest that you should usually use
BeginInvoke. That way you don’t need to worry about deadlock, for example – but you need to understand that the UI may not have been updated by the time you next look at it! In particular, you shouldn’t modify data which the UI thread might be about to use for display purposes. For example, if you have aPersonwithFirstNameandLastNameproperties, and you did:Then the UI may well end up displaying ‘Keyser Spacey’. (There’s an outside chance it could display ‘Kevin Soze’ but only through the weirdness of the memory model.)
Unless you have this sort of issue, however,
Control.BeginInvokeis easier to get right, and will avoid your background thread from having to wait for no good reason. Note that the Windows Forms team has guaranteed that you can useControl.BeginInvokein a ‘fire and forget’ manner – i.e. without ever callingEndInvoke. This is not true of async calls in general: normally every BeginXXX should have a corresponding EndXXX call, usually in the callback.