Polling for Asynchronous Call Completion

Polling for Asynchronous Call Completion


The IsCompleted property of the IAsynResult returned by the BeginInvoke can be used to determine when the asynchronous call completes.Polling for completion allows
the calling thread to continue executing while the asynchronous call executes on a ThreadPool thread



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(5000, out ThreadId, null, null);

            // 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();
        }
    }

}

Comments

Popular posts from this blog

Authentication and Authorization in Web API -Part1

My Gardening Journey 6