Posts Tagged ‘delegates’

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.

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.

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:

//this will block until the asynchronous operation is complete
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.