In a form, compare
BeginInvoke (new Action (() => {
MessageBox.Show ());
}));
with
Invoke (new Action (() => {
MessageBox.Show ());
}));
What is the difference, and when should I use one over the other? How is the behavior affected by the message pump of the MessageBox?
I did some testing and found that both methods block the UI.
The only difference is that Invoke is actually called instantly while BeginInvoke takes a (very short) time until the code is run. This is to be expected.
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.
BeginInvoke(Action) Executes the specified delegate asynchronously on the thread that the control's underlying handle was created on. BeginInvoke(Delegate) Executes the specified delegate asynchronously on the thread that the control's underlying handle was created on.
BeginInvoke
will invoke the delegate asynchronously, returning immediately having queued the delegate for execution independently of the current thread.
Invoke
will invoke the delegate synchronously, blocking the calling thread until the delegate completes.
To see the difference, try the following code:
BeginInvoke(new Action(()=>Console.WriteLine("BeginInvoke")));
Console.WriteLine("AfterBeginInvokeCalled");
Invoke(new Action(()=>Console.WriteLine("Invoke")));
Console.WriteLine("AfterInvokeCalled");
You should see output similar to the following, where the "BeginInvoke" text is delayed due to its asynchronous execution:
AfterBeginInvokeCalled
Invoke
AfterInvokeCalled
BeginInvoke
Regarding the behaviour you observe, as it is only the act of calling the delegate that is synchronous or asynchronous; the content of the method may well cause the calling thread to stop or the UI to be blocked. In the case of showing a message box, regardless of whether the delegate is delayed using BeginInvoke
or not, once the delegate is called, the UI will be blocked until the message box is dismissed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With