|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer|
Asynchronous Programming Using Delegates
Asynchronous delegates allow you to call a synchronous method in an asynchronous manner. When you call a delegate synchronously, the Invoke method calls the target method directly on the current thread. If the compiler supports asynchronous delegates, it will generate the Invoke method and the BeginInvoke and EndInvoke methods. If the BeginInvoke method is called, the common language runtime (CLR) will queue the request and return immediately to the caller. The target method will be called on a thread from the thread pool. The original thread, which submitted the request, is free to continue executing in parallel with the target method, which is running on a thread pool thread. If a callback method has been specified in the call to the BeginInvoke method, the callback method is called when the target method returns. In the callback method, the EndInvoke method obtains the return value and any in/out parameters. If no callback method is specified when calling BeginInvoke, EndInvoke can be called from the thread that called BeginInvoke.
Compilers should emit delegate classes with Invoke, BeginInvoke, and EndInvoke methods using the delegate signature specified by the user. The BeginInvoke and EndInvoke methods should be decorated as native. Because these methods are marked as native, the CLR automatically provides the implementation at class load time. The loader ensures that they are not overridden.
In This Section
Discusses using delegates to asynchronously call synchronous methods.
- Asynchronous Delegates Programming Sample
Demonstrates the use of asynchronous delegates in a simple sample, which factorizes numbers.