Tag Archives: EndInvoke

Asynchronous Programming

Asynchronous Programming

When you create delegate, the compiler generates three methods Invoke, BeginInvoke, EndInvoke. Invoke is used to execute delegate synchronously, and rest two methods allow you to have asynchronous programming.

BeginInvoke takes the same parameters as delegate itself, plus another two parameters- an AsyncCallback which is called after the BeginInvoke execution, and an object parameter which is made available through the AsyncState property of the IAsyncResult parameter which is passed to the AsyncCallback.

The call to BeginInvoke returns an IAsyncResult which can be used to call EndInvoke, and you don’t have to pass a callback delegate to be executed if you don’t want to – just pass null as the last but one parameter to BeginInvoke.

private delegate int DoubleMeDelegate(int x);

protected void Page_Load(object sender, EventArgs e)

{

   for (int i = 1; i < 5; i++)

  {

     DoubleMeDelegate d = new DoubleMeDelegate(DoubleMe);

     d.BeginInvoke(i, new System.AsyncCallback(InvokeMessage), d);

   }

Thread.Sleep(1900);

}

private void InvokeMessage(IAsyncResult ar)

{

   DoubleMeDelegate dEnd = (DoubleMeDelegate)ar.AsyncState;

   int result = dEnd.EndInvoke(ar);

   Response.Write(result + “<br/>”);

}

private int DoubleMe(int single)

{

   Thread.Sleep(100);

   return (2 * single);

}

Leave a comment

Filed under C#