Navigation

Saturday 14 September 2013

Calling synchronous method asynchronously in .Net 3.5

  • We can call the methods asynchronously using custom  delegate that has an exact signature of method that you want to call asynchronously.
  • To know the completion status of the asynchronous method AsyncCallback delegate can be used.
      Below example illustrates the Asynchronous method execution.


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

namespace AsyncDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            AsyncDemo ad = new AsyncDemo();

            AsyncDelegate asyncDelegate = new AsyncDelegate(ad.AsyncDelegate);

            AsyncCallback callback = new AsyncCallback(ad.Status);

            IAsyncResult result = asyncDelegate.BeginInvoke(callback, null);

            Console.WriteLine("Async method execution is running and status of completion is {0}", result.IsCompleted);
            Console.ReadLine();

        }
    }

    public delegate void AsyncDelegate();


    public class AsyncDemo
    {
        /// <summary>
        /// Method that executes asynchronously
        /// </summary>
        public void AsyncDelegate()
        {
            int a = 0;
            for (int i = 0; i < 2000000000; i++)
            {
                a += i;
            }
            Console.WriteLine("total  {0}", a);
        }

        /// <summary>
        /// Callback method that is invoked after the completion of async method execution
        /// </summary>
        /// <param name="result"></param>
        public void Status(IAsyncResult result)
        {
            Console.WriteLine("Async method execution is completed");
        }
    }
}



For more information follow the link http://msdn.microsoft.com/en-us//library/2e08f6yc.aspx

No comments:

Post a Comment