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);
Invoke() calls the method synchronously,
and the caller has to wait until the delegate finishes executing (a standard
delegate invocation in C# calls
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
to optionally specify a delegate to execute by the ThreadPool thread just
before it returns, and an arbitrary object to hold state. The
signature is a void method with a single
which lets you access information about the call.
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 ...