Author : Admin
Last Modified : 23-Aug-2020
Complexity : Beginner

Asynchronous delegates [Calling Synchronous Methods Asynchronously]


.Net Framework provides the mechanism to execute methods asynchronously, Asynchronous delegates solve the problem of calling the method asynchronously and pass the parameter and get the result in return when complete.
To do this we need to define a delegate, the delegate has the same signature which the method has, there are two methods BeginInvoke and EndInvoke.


There are following entities
BeginInvoke : 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. 1) AsynCallback Delegate and 2) User Define object

  • AsynCallback Delegate (Optional) - it references the method which is called when Asynchronous call completes.
  • User Define object (Optional) - It is passed to the callback method, which got in AsyncState of IAsyncResult.

EndInvoke : It uses to get the result of Asynchronous call, it is used after BeginInvoke any time. EndInvoke blocks the calling thread until Asynchronous call is completed.
IAsynResult : The BeginInvoke return the IAsynResult, from this we can track the progress of the asynchronous call.

See below example How to use BeginInvoke

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

namespace AsynchronousDelegates
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<string, string, int> method = Sum;
            IAsyncResult asynResult = method.BeginInvoke("1", "2", null, null);
            var result = method.EndInvoke(asynResult);
            Console.WriteLine(result);           
            Console.Read();
        }
        static int Sum(string a, string b)
        {
            return Convert.ToInt32(a) + Convert.ToInt32(b);
        }
    }
}

See below example Use of Callback Delegate and Pass User Define Object

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

namespace AsynchronousDelegates
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<string, string, int> method = Sum;
            IAsyncResult asynResult = method.BeginInvoke("1", "2", SumRes, method);
            var result = method.EndInvoke(asynResult);
            Console.Read();
        }
        private static void SumRes(IAsyncResult ar)
        {
            var target = (Func<string, string, int>)ar.AsyncState;
            int result = target.EndInvoke(ar);
            Console.WriteLine("sum is: " + result);
        }
        static int Sum(string a, string b)
        {
            return Convert.ToInt32(a) + Convert.ToInt32(b);
        }
    }
}