Re: Delegate.BeginInvoke and EndInvoke.

Peter Ritchie <[email protected]> Tue, 15 Jan 2008 13:08:01 -0500
Newsgroups gmane.comp.windows.devel.dotnet.winforms
Message-ID <LISTSERV%[email protected]>
The only EndInvoke that I know of where you're not "required" to call it
is Control.EndInvoke.

See the comments in
http://blogs.msdn.com/cbrumme/archive/2003/05/06/51385.aspx

There are various object that are kept around until EndInvoke is called,
depending on the delegate this may include return value, exception(s),
state, etc.

In your timed-out case, you'll force the thread to block until the
delegate has completed running, which probably defeats the purpose of
timing-out.

You could spawn another thread that waits on the AsyncWaitHandle and
simply calls EndInvoke when it becomes signaled.  That way you free your
current thread to time-out and the EndInvoke is handled in the
background.  It could very well be there's an example of this somewhere...

On Tue, 15 Jan 2008 10:17:09 -0700, Bhatnagar, Amit
<[email protected]> wrote:

>I have made a service to timeout a method call by launching a delegate
>asynchronously via BeginInvoke. The documentation states, indirectly,
>that the call to BeginInvoke should be followed by a call to EndInvoke
>to prevent leaks. However, I am not sure if the call to EndInvoke is
>required should the delegate timeout because the call to EndInvoke will
>block the thread and wait for the delegate to complete. So I think what
>I have is OK, but can anyone confirm if the call to EndInvoke is
>required if it timesout?
>
>See the following code:
>
>---
>IAsyncResult asyncResult = d.BeginInvoke(null, new object());
>
>if (asyncResult.AsyncWaitHandle.WaitOne(7000, true))
>{
>   // Not timed out...
>   d.EndInvoke(asyncResult);
>}
>
>else
>{
>   //Timed out ... EndInvoke required here?
>}
>