BeginInvoke and Invoke

  • Thread starter Thread starter Nick
  • Start date Start date
N

Nick

Hi all,

Are the two snippets below equivelent, since they both only continue
once the ShowForm method returns???

1.
delShowForm del = new delShowForm(ShowForm); //show form shows a form
IAsyncResult asyncResult = this.BeginInvoke(del);
asyncResult.AsyncWaitHandle.WaitOne();
this.EndInvoke(asyncResult);

2.
delShowForm del = new delShowForm(ShowForm); //show form shows a form
this.Invoke(del);


Thanks for any explaination
Nick
 
They seem to be equivalent. But, in general, using BeginInvoke in such a
context ensures your worker thread wouldn't block if the main UI thread is
showing a modal window or is busy and cannot retrieve and dispatch messages
from the window message queue.

Also note that in Snippet #1 you can do some useful work after you've called
BeginInvoke and before you start waiting for the async call to complete.
 
Hi Nick,

I assume we are talking about Control's BeginInvoke and Invoke methods.

1. If they are called form a thread different than the UI thread owning the
underlaying windows control handler
(for example they are called form a worker thread).
The effect of both will be the same. I belive the form with Invoke as
preferable because it is shorter and more readable. The form with
BeginInvoke is useful when you want to do some work between the momends of
calling the ShowForm method and polling the result.

2. When those two are called form the UI thread that owns the form they have
different behaviour:
- Using Invoke dosen't make sense. you can call the ShowForm method
directly.
- Using BeginInvoke in the same way like in your example will cause
deadlock. Because of the WaitOne() call.
Removing the line with WaitOne will bring us to the first case with invoke,
which is senseless.
BeginInvoke in the case of not polling the result could be verry useful if
you want to have PostMessage-like behaviour.

HTH
B\rgds
100
 
Back
Top