Wednesday, February 04, 2009

Call method Asynchronously using delegate in C#

The .NET Framework enables you to call any method asynchronously. To
do this you 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 initiates the asynchronous call. It has the
same parameters as the method that you want to execute
asynchronously, plus two additional optional parameters. The first
parameter is an AsyncCallback delegate that references a method to be
called when the asynchronous call completes. The second parameter is
a user-defined object that passes information into the callback
method. 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 asynchronous call.

The EndInvoke method retrieves the results of the asynchronous
call. It can be called any time after BeginInvoke. If the
asynchronous call has not completed, EndInvoke blocks the calling
thread until it completes. The parameters of EndInvoke include the
out and ref parameters of the method that you want to execute
asynchronously, plus the IAsyncResult returned by BeginInvoke.

Below is the Class “AsyncDemo” which demonstrate how to call
method in async mode.


class AsyncDemo

{


//This will point to any method which has two integer arguments.

private delegate int MyDelegate(int input1, int input2);

//Variable of above mention delegate.


MyDelegate mDeleg;

private int Calc(inta, int b)

{


System.Threading.Thread.Sleep(new System.TimeSpan(0, 0, 0, 5, 0));

return a + b;


}


private void CalcCallback(IAsyncResult ar)


{


int answer = mDeleg.EndInvoke(ar);

string sss = ar.AsyncState as string;

}





public void MyDemo()

{


mDeleg = new MyDelegate(Calc);

AsyncCallback callback = new AsyncCallback(CalcCallback);

int input1 = 111;

int input2 = 222;


string strResult = null;

mDeleg.BeginInvoke(input1, input2, callback, "Tejas");

}

}

Below is the image of the above class in the assembly.Shows how BeginInvoke() and EndInvoke() is generated by CLR.