Executing a CallBack Method , When a Asynchronous call Completed.

Executing  a CallBack Method , When  a Asynchronous call Completed.


If the thread that initiates the asynchronous call does not need to be the thread that processes the results, you can execute a callback method when the call completes. The callback method is executed

on a ThreadPool thread.

To use a callback method, you must pass BeginInvoke an AsyncCallback delegate that represents the callback method. You can also pass an object that contains information to be used by the callback

method. In the callback method, you can cast the IAsyncResult, which is the only parameter of the callback method, to an AsyncResult object. You can then use the AsyncResult.AsyncDelegate property

to get the delegate that was used to initiate the call so that you can call EndInvoke.


Delegate's do this asynchronous call invocation using delegate's BeginInvoke method.
First we have to define a delegate with the same signature as the method we want to call. The common language runtime automatically defines BeginInvoke and EndInvoke methods for this delegate, with

the appropriate signatures. If a callback method has been specified in the call to the BeginInvoke method, the callback method is called when the target method ends. In the callback 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.

   1) The threadId parameter of TestMethod is an out parameter (<Out> ByRef in Visual Basic), so its input value is never used by TestMethod. A dummy variable is passed to the BeginInvoke call. If  

the threadId parameter were a ref parameter (ByRef in Visual Basic), the variable would have to be a class-level field so that it could be passed to both BeginInvoke and EndInvoke.

   2) The state information that is passed to BeginInvoke is a format string, which the callback method uses to format an output message. Because it is passed as type Object, the state information must

be cast to its proper type before it can be used.

   3) The callback is made on a ThreadPool thread. ThreadPool threads are background threads, which do not keep the application running if the main thread ends, so the main thread of the example has

to sleep long enough for the callback to finish.

Extracts from : http://jaliyaudagedara.blogspot.in/2012/06/asynchronous-programming-and-callback.html
            https://msdn.microsoft.com/en-us/library/2e08f6yc%28v=vs.110%29.aspx,

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);
            int dummy = 0;
            //Initiate the Asynchronous call
    /*In here, the first parameter is the methods parameter.
    The second parameter is an AsyncCallback delegate that references a method to be called when the asynchronous call completes.
    The third parameter is a user-defined object that passes information into the callback method.*/
            IAsyncResult result = caller.BeginInvoke(5000, out dummy, new AsyncCallback(CallbackMethod), "The call executed on thread {0}, with return value \"{1}\".");

            // IsCompleted is a property of IAsyncResult.
            /*while (result.IsCompleted == false)
            {
                Thread.Sleep(230);
                Console.Write(".");
            }*/

            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();*/
            Console.ReadLine();


        }

        static void CallbackMethod(IAsyncResult ia)
        {
            // Retrieve the delegate.
            System.Runtime.Remoting.Messaging.AsyncResult result = (System.Runtime.Remoting.Messaging.AsyncResult)ia;
            AsyncMethodToBeExecutedAsyn result_ = (AsyncMethodToBeExecutedAsyn)result.AsyncDelegate;

            // Retrieve the format string that was passed as state 
            // information.
            string formatString = (string)ia.AsyncState;

            // Define a variable to receive the value of the out parameter.
            // If the parameter were ref rather than out then it would have to
            // be a class-level field so it could also be passed to BeginInvoke
            int threadId = 0;

            // Call EndInvoke to retrieve the results.
            string returnValue = result_.EndInvoke(out threadId, ia);


            // Use the format string to format the output message
            Console.WriteLine(formatString, threadId, returnValue);
            Console.ReadLine();



        }


    }

}

Comments

Popular posts from this blog

Authentication and Authorization in Web API -Part1

My Gardening Journey 6