I want to call a method asynchronously in a synchronous environment. ie the subsequent lines should execute immediately after the method call regardless how much time the method takes to execute.
When we execute the above code it will result as follows.
But what I want is
The immediate answer
If we ask this question to any developer the immediate answer will be “use threading”.Yes that is correct we can use threading.But is there an other easier solution?
I was in the category of saying “threading” until I heard about the async method invocation using delegates.Here goes the solution.
- Create a delegate to match with your long running method signature.
- Declare a delegate variable and instantiate it by passing the address of the long running method.
- Call the BeginInvoke Method of the delegate which calls the pointed method in asynchronous fashion.
You can pass type safe parameters into this methods.For that just change the delegate signature.This automatically ask you to change the function which you are passing into delegate.
Processing return values in async method invocation
When we execute a method we might be expecting some values back after the processing.Now lets see how to get the return value.First change the signature of the method such that it returns something.Obviously return the value.
Now comes a new delegate named AsyncCallback which points to the async delegate execution completed method.We need to pass this delegate variable to the InvokeAsync method of our delegate.
The completed method should accept one parameter of type IAsyncResult which is must when we point using AsyncCallback.The importance of this variable comes when we need the return value.
First we need to cast to AsyncResult which is the concrete implementation of IAsyncResult.Then get the AsyncDelegate property which is our delegate and call the EndInvoke method on that.Confused??The change is only in the completed method where we process the return value.See the below code to get clarified.
Uploaded a sample here