There are several patterns to call a synchronous method asynchronously as shown below.
1- BeginInvoke and EndInvoke
BeginInvoke and EndInvoke Pattern
As you see that first message written in console is worked in main thread (ThreadID is 1), But, DoWork() method is called asynchronously, so that, second message is worked on different thread (ThreadID is 3).
DoWork() method returns int value and without parameters, so that, BeginInvoke method shows two parameters(callback, @object) as shown in Figure-2
Notice that EndInvoke() method takes asyncResult variable returned by BeginInvoke() method and it also returns int value because of Func delegate in Figure-3.
If method has some parameters, first parameters of BeginInvoke() method will be same as shown in Figure-5.
Notice that DoWork() method is not used directly, it is encapsulated with a delegate. I used
Func<int, int, int> delegate which is signature of DoWork() method in this code.
Let’s examine declaration of DoWork() method below. you see that there are two int parameters and returns int type.
int DoWork(int num1, int num2) is equals to Func<int, int, int>
Let’s use our delegate MethodCaller
Let’s see how to use anonymous delegate asynchronously.
I will always use anonymous delegates in examples from now on. Below code will also show using delegate with lambda notation.
You can perform additional processing before or after the asynchronous call complete using WaitHandle.
Use Polling for completion allows the calling thread to continue executing while the asynchronous call executes on a ThreadPool thread.