Monday, June 13, 2005

Asynchronous programming in .NET

The .NET API makes asynchronous programming a breeze....
U can make a async call to any method and what amazed me was the simplicity !!!

We just have to make use of the magic of delegates...
Define a delegate with the same signature as the method you want to call; the common language runtime automatically defines BeginInvoke and EndInvoke methods for this delegate, with the appropriate signatures.
The BeginInvoke method is used to initiate the asynchronous call. It has the same parameters as the method you want to execute asynchronously, plus two additional parameters that will be described later. BeginInvoke returns immediately and does not wait for the asynchronous call to complete. BeginInvoke returns an IasyncResult, which can be used to monitor the progress of the call.
The EndInvoke method is used to retrieve the results of the asynchronous call. It can be called any time after BeginInvoke; if the asynchronous call has not completed, EndInvoke will block until it completes. The parameters of EndInvoke include the out and ref parameters ( ByRef and ByRef in Visual Basic) of the method you want to execute asynchronously, plus the IAsyncResult returned by BeginInvoke.

So after making a Async call, we have the following options:
  1. Do something and then block till the call completes.
  2. Poll continously to see it call is complete
  3. Assign a call-back delegate (AsyncCallBack)

I found this feature of .NET really really cool...especially in my threading applications.