Asynchronous Programming Using Delegates

Asynchronous Programming Using Delegates 

Delegates can be used to call the Synchronous methods in a Asynchronous manner .When we call the delegate synchronously The invoke method is calls the target method directly on the main thread.If the BeginInvoke method is called the "common language runtime" queues the request and returns immediatly to the caller.The target method is called asynchronously on a thread from a thread pool.The original thread
which submitted the request is now free and can execute in parallel to the target Thread.If a callback method is specified on the in the call to the BeginInvoke method,the callback  method is called when the target method ends.In the Call Back method the EndInvoke Method obtains the return value and any input/output or output only parameters. If no callback method is specified when calling BeginInvoke ,EndInvoke can be called  from the thread that called BeginInvoke. The .Net Framework thus enables calling method Asynchronously with the help of delegates.A delegate is defined with the same signature  as the method
The CLR automatically defines BeginInvoke and EndInvoke methods for this delegate , with appropriate signatures. The BeginInvoke  method initiates the Asynchronous call.It has the same signature as the method that you want to invoke plus the addition of two extra parameters .

    1).The First parameter is the AsyncCallBack delegate that references a method to be called when the  asynchronous call completes.
    2).The Second parameter is a user defined objects that passes the information into the callback method.

BeginInvoke returns immediately and does not wait for the asynchronous call to complete.
BeginInvoke returns an IAsyncResult, which can be used to monitor the progress of the asynchronous call.

The EndInvoke method retrieves the results of the asynchronous call. It can be called any time after BeginInvoke. If the asynchronous call has not completed, EndInvoke blocks the calling thread until it completes. The parameters of EndInvoke include the out and ref parameters (<Out> ByRef and ByRef in Visual Basic) of the method that you want to execute asynchronously,
 plus the IAsyncResult returned by BeginInvoke


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

namespace ManualResetEvent_
{

    /*  class definition containing the target method */
    /*  Method that needs to be called Asynchrounously*/
    public class AsynMethodCall
    {
        public string MethodToBeExecutedAsyn(int callDuration, out int ThreadId)
        {
            Console.WriteLine(" My Method on a thread started");
            Thread.Sleep(callDuration);
            ThreadId = Thread.CurrentThread.ManagedThreadId;
            return String.Format("My call time was {0}.", callDuration.ToString());
        }

    }

    /* The definition of the Delegate Signature */
    public delegate string AsyncMethodToBeExecutedAsyn(int callDuration, out int ThreadId);
   

    public class AsynchrounousProgram
    {
        public static void Main()
        {

            // The asynchronous method puts the thread id here where it executes
            int ThreadId;

            // Create an instance of the AsynMethodCall class.
            AsynMethodCall objectsAsync = new AsynMethodCall();

            // Create the delegate.
            AsyncMethodToBeExecutedAsyn caller = new AsyncMethodToBeExecutedAsyn(objectsAsync.MethodToBeExecutedAsyn);

            //Initiate the Asynchronous call
            IAsyncResult result = caller.BeginInvoke(3000, out ThreadId, null, null);

            Console.WriteLine("Main thread will now perform some work ");
            Thread.Sleep(1000);
            //Thread.CurrentThread.ManagedThreadId -- to get the thread Id on which it is executed //
            Console.WriteLine("Main thread did some work on the thread {0}",Thread.CurrentThread.ManagedThreadId);

            string returnresult = caller.EndInvoke(out ThreadId, result);
            Console.WriteLine("The Target method  executed on Thread {0}  and the return value \"{1}\" ",ThreadId,returnresult);
            Console.ReadLine();
        }
    }

}







Comments

Popular posts from this blog

Authentication and Authorization in Web API -Part1

My Gardening Journey 6