O'Reilly logo

C# in a Nutshell by Peter Drayton, Ted Neward, Ben Albahari

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Asynchronous Delegates

Sometimes it is desirable to call a method asynchronously, so the call returns immediately while the method executes on a separate thread. The runtime provides a standard way that any method can be called asynchronously, taking into account retrieving return values and ref/in parameters supplied to the method. When the C# compiler encounters a delegate, the delegate derived class it generates contains three key methods:

return-type Invoke (parameter-list);
IAsyncResult BeginInvoke (parameter-list, AsyncCallback ac, object state);
return-type EndInvoke (ref/out-only parameter-list, IAsyncCallback ac);

Calling Invoke() calls the method synchronously, and the caller has to wait until the delegate finishes executing (a standard delegate invocation in C# calls Invoke()).

Calling BeginInvoke() invokes the delegate with the supplied parameter list, then immediately returns. This asynchronous call is performed as soon as a thread is available in the ThreadPool. Two additional parameters are added to BeginInvoke(): an AsyncCallback object, to optionally specify a delegate to execute by the ThreadPool thread just before it returns, and an arbitrary object to hold state. The AsyncCallback delegate signature is a void method with a single IAsyncResult parameter, which lets you access information about the call.

Calling EndInvoke() retrieves the return value of the called method, along with any ref/out parameters that may have been modified.

In the following example, we call ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required