Wednesday, October 29, 2014

Asynchronous Delegates

As the title the asynchronous delegate refer to invoke a function in async manner. The declaration is same as normal delegate.

        public delegate void mydelegate(string s);


Next thing we need a method to assign it in delegate invocation list. So I create a method named Function and sleep this method for 5 second to give an effect that this method need 5 second to  execute.

    class ABC
    {
        public void Function(string s)
        {
            System.Threading.Thread.Sleep(TimeSpan.FromSeconds(5));
            Console.WriteLine(s);
        }
    }


We need a another method which get executed after delegate invoked. This will be our callback method.

        
        static void callback(IAsyncResult result)
        {
            Console.WriteLine("delegate finished");
        }



Final thing we need is to create an instance of this delegate and assign the method to its invocation list and then start the invocation with BeginInvoke method.

        ABC a = new ABC();
        mydelegate del = new mydelegate(a.Function);

        IAsyncResult result = del.BeginInvoke("i am delegate", new AsyncCallback(callback), null);



If you see the BeginInvoke invoke method it has three argument. First one is the parameter need to send to the delegate method. Second is to attached and callback event. And last is the state. Here we leave it null. If your method has more than one parameter then number of parameters in BeginInvoke will increase. BeginInvoke starts the method execution in async manner. And the same time the caller method also runs. So we need some thing in caller method that make it wait for delegate method to finish. EndInvoke resolves this purpose.

        del.EndInvoke(result);

Here is the complete code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestDelegate
{
    class Program
    {
        public delegate void mydelegate(string s);
        static void Main(string[] args)
        {
            Console.WriteLine("-Start program-");
            ABC a = new ABC();
            mydelegate del = new mydelegate(a.Function);
            Console.WriteLine("delegate initilized");
            IAsyncResult result = del.BeginInvoke("I am Delegate",new AsyncCallback(callback), null);
            Console.WriteLine("main running");
            del.EndInvoke(result);
            Console.ReadLine();
        }

        static void callback(IAsyncResult result)
        {
            Console.WriteLine("delegate finished");
        }
    }

    class ABC
    {
        public void Function(string s)
        {
            System.Threading.Thread.Sleep(TimeSpan.FromSeconds(5));
            Console.WriteLine(s);
        }
    }
}


Output:
-Start program-    
delegate initilized
main running       
I am Delegate      
delegate finished 

 
Happy Coding ... :)