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 ...

Get C# in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.