Another useful feature of delegates is the ability to execute a method asynchronously. That is, through a delegate, you can begin invocation of a method and then return immediately while the delegate executes its method in a separate thread. Your page execution does not need to wait for that method to complete.
The following example demonstrates the use of delegates for asynchronous method invocation. To see this in action we need a method that simulates a lengthy operation, such as writing data to db logs, record page hits that can be asynchronous, and do not affect the end client response.
public delegate void LongTimeTask_Delegate(string s);
protected void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
{
LongTimeTask_Delegate d = null;
d = new LongTimeTask_Delegate(LongTimeTask);
IAsyncResult R = null;
R = d.BeginInvoke("TestString", null, null);
}
}
In the above load event of the page after binding all the UI controls we need to perform a lengthy operation to record something in DB or any IO operation file. We are initializing the deligate with the LongTimeTask method, and delegate.BeginInvoke will call the method below asynchronously. Later we will see how to know if the method invokation completed successfully or not.
public void LongTimeTask(string s)
{
}
Now, if we would want to perform an another operation after the above method is completed, That is called callback approach, add the async call back event in beginInvoke:
R = d.BeginInvoke("TestString", new AsyncCallback(TaskCompleted), null);
public void TaskCompleted(IAsyncResult R)
{
}
The above method will execute on completion of LongTimeTask method.
We can also wait untill the LongTimeTask is execution is completed or not, but then that will not serve the purpose of calling it asynchronously, but still you would need it somewhere:
d.EndInvoke(R);
Try it out at your end, I have just given you the skeleton that I have tried, It works fine, but just be careful, as this works on a separate thread, which might sometimes consumes a lot of memory / CPU usage.