Asynchronous Nature of Delegates



Introduction

Building a multithreaded application can be done in several ways includes:

  1. Asynchronous delegates calls.
  2. The BackgroundWorker component.
  3. The Thread class.

In this article we will cover the asynchronous delegates calls, if you want to know about other two types see my articles (Using the BackgroundWorker component, Building a multithreaded application using Thread calss).

This article assumes that you have a good understanding of the delegate type, if you don't, see my article Delegates in C#.
Asynchronous delegates calls:
as you may know, we use the delegate to point to method in the application, which can be invoked at later time.

Example 1:

namespace DelegateSynchronousCalls

{

    public delegate int MyDelegate(int x);

    public class MyClass

    {

        //A method to be invoke by the delegate

        public int MyMethod(int x)

        {

            return x * x;

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            MyClass myClass1 = new MyClass();

            MyDelegate del = new MyDelegate(myClass1.MyMethod);

 

            //invoke the method synchronously

            int result = del(5);

            //this text will not show till the first operation finish

            Console.WriteLine("Proccessing operation...");

            Console.WriteLine("Result is: {0}", result);

            Console.ReadLine();

        }

    }
}

As you can see we used our delegate to invoke the method in the main thread of our application, but what if we have a long runing proccess that will be executed when we invoke the method, for example:

public
int MyMethod(int x)

{

    //simulate a long running proccess

    Thread.Sleep(10000);

    return x*x;   

}

We have now an operation that will take about 10 second to complete so our application will be not responsive and we can't execute any other operations till the first one finish.

So, what we can do to overcome this problem?

The answer is to use the delegate to invoke the method asynchronosly, but how we can do this?. The next example will show you how to use our delegate to make asynchronous call of the method.

Example 2:

namespace
DelegatesAsynchronousCalls

{

    class Program

    {

        public delegate int MyDelegate(int x);

        public class MyClass

        {

            //A method to be invoke by the delegate

            public int MyMethod(int x)

            {

                //simulate a long running proccess

                Thread.Sleep(10000);

                return x * x;

            }

        }

        static void Main(string[] args)

        {

            MyClass myClass1 = new MyClass();

            MyDelegate del = new MyDelegate(myClass1.MyMethod);

            //Invoke our method in another thread

            IAsyncResult async = del.BeginInvoke(5, null, null);

            //do something while MyMethod is executing.

            Console.WriteLine("Proccessing operation...");

            //recieve the results.

            int result = del.EndInvoke(async);

            Console.WriteLine("Result is: {0}", result);

            Console.ReadLine();

        }

    }

}

As you can see, we defined the delegate as usual but we don't start invoking our method directly, we used our delegate to call BeginInvoke() method that returns an IAsyncResult object, then we submit this object to the EndInvoke() method then EndInvoke() provide the return value.(complex right !!?)

You may wonder now from where all this methods come from?

The answer is simple, when you define a delegate, a custom delegate class is generated and added to your assembly. this class include many method like Invoke(), BeginInvoke() and EndInvoke().

When you use your delegate to call a method you actualy call the Invoke() method. Invoke() method executes your method synchronously (on the main thread) as in example 1.

When you want to make an asynchronous call to your underlying method first you call BeginInvoke(). When you call BeginInvoke() your method is queued to start on another thread. 

BeginInvoke() doesn't return the return value of the underlying method. Instead it returns an IAsyncResult object that you can use to determine when the asynchronous operation is complete.

To take your results, you submit the IAsyncResult object to the EndInvoke() method of the delegate. EndInvoke() waits for the operation to complete if it hasn't already finished and then provide the return value.

You may ask, what is the other two parameters in the BeginInvoke() method?

When calling BeginInvoke() you supply all the parameters of the original method, plus two parameters, the first can be used in callback and the othe is a state object. if you don't need these options just pass a null reference.

In the next section you will see how to use them.

Using AsyncCallback delegate:

To alow the calling thread to know if the asynchronous operation has completed its work, you have two ways to do this, first you can make use of the IsCompleted property of the IAsyncResult interface.

By using this property, the calling thread is able to determine is the asynchronous operation has completed before calling EndInvoke(). If the method has not completed, IsCompleted returns false. If IsCompleted return true, the calling thread can obtain the results

Example 3:

namespace DelegatesAsyncCallsIsCompleted

{

    public delegate int MyDelegate(int x);

    public class MyClass

    {

        //A method to be invoke by the delegate

        public int MyMethod(int x)

        {

            //simulate a long running proccess

            Thread.Sleep(3000);

            return x * x;

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            MyClass myClass1 = new MyClass();

            MyDelegate del = new MyDelegate(myClass1.MyMethod);

            //Invoke our methe in another thread

            IAsyncResult async = del.BeginInvoke(5, null, null);

 

            //loop until the method is complete

            while (!async.IsCompleted)

            {

                Console.WriteLine("Not Completed");

            }

            int result = del.EndInvoke(async);

            Console.WriteLine("Result is: {0}", result);

            Console.ReadLine();

        }

    }

}

It would be more efficient when we have a delegate that inform the calling thread when the operation is finished.

To do this, you need to supply an instance of the AsyncCallback delegate as a parameter to BeginInvok(). This delegate will call a specified method automaticaly when the asynchronous call has completed.

The method that AsyncCallback will invoke must taking IAsyncResult as a sole parameter and return nothing.

public
static void MyCallBack(IAsyncResult async)

{

}

The IAsyncResult is the same object that you recieve when you call BeginInvoke() method.

Example 4:

namespace
AsyncCallbackDelegate

{

    public delegate int MyDelegate(int x);

    public class MyClass

    {

        //A method to be invoke by the delegate

        public int MyMethod(int x)

        {

            //simulate a long running proccess

            Thread.Sleep(10000);

            return x * x;

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            MyClass myClass1 = new MyClass();

            MyDelegate del = new MyDelegate(myClass1.MyMethod);

            //Invoke our methe in another thread

            IAsyncResult async = del.BeginInvoke(5, new AsyncCallback(MyCallBack), null);

            Console.WriteLine("Proccessing the Operation....");

            Console.ReadLine();

        }

        static void MyCallBack(IAsyncResult async)

        {

            Console.WriteLine("Operation Complete);

        }

    }

}

Remember, the MyCallback() method will be invoked by the AsyncCallback delegate when the MyMethod() has completed.
As you can see, we didn't invoke the EndInvoke() method that because the MyCallback() method doesn't have access to the MyDelegate object, so we can make use of the incoming IAsyncResult parameter and cast it into type AsyncResult and use the static AsyncDelegate property which returns a reference to the original asynchronous delegate that was created else where.

We can rewrite the MyCallback() method as follow:

static
void MyCallBack(IAsyncResult async)

{

    AsyncResult ar = (AsyncResult)async;

    MyDelegate del = (MyDelegate)ar.AsyncDelegate;

    int x = del.EndInvoke(async);

    Consol.WriteLine("Operation Complete, Result is: {0}", x);

}


The final parameter of the BeginInvoke() method can be used to pass additional state information to the callback method from the primary thread. Because this parameter is a System.Object, you can pass in any type of information .
Exampe 5:

namespace
AsyncCallbackDelegate

{

    public delegate int MyDelegate(int x);

    public class MyClass

    {

        //A method to be invoke by the delegate

        public int MyMethod(int x)

        {

            //simulate a long running proccess

            Thread.Sleep(10000);

            return x * x;

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            MyClass myClass1 = new MyClass();

            MyDelegate del = new MyDelegate(myClass1.MyMethod);

            //Invoke our methe in another thread

            IAsyncResult async = del.BeginInvoke(5, new AsyncCallback(MyCallBack), "A message from the main thread");

            Console.WriteLine("Proccessing the Operation....");

            Console.ReadLine();

        }

        static void MyCallBack(IAsyncResult async)

        {

            AsyncResult ar = (AsyncResult)async;

            MyDelegate del = (MyDelegate)ar.AsyncDelegate;

            int x = del.EndInvoke(async);

 

            //make use of the state object.

            string msg = (string)async.AsyncState;

            Console.WriteLine("{0}, Result is: {1}", msg, x);

        }

    }

}

I hope this article helped you a little bit in understanding the asynchronous nature of delegates. See you.

Up Next
    Ebook Download
    View all
    Learn
    View all