Execute a Method Asynchronously Blocking - CSharp Thread Asynchronous

CSharp examples for Thread Asynchronous:Async

Description

Execute a Method Asynchronously Blocking

Demo Code


using System;/*from ww  w. ja  v a2 s.  c om*/
using System.Threading;
using System.Collections;

class MainClass
    {
        private static void TraceMsg(DateTime time, string msg)
        {
            Console.WriteLine("[{0,3}/{1}] - {2} : {3}",
                Thread.CurrentThread.ManagedThreadId,
                Thread.CurrentThread.IsThreadPoolThread ? "pool" : "fore",
                time.ToString("HH:mm:ss.ffff"), msg);
        }

        public delegate DateTime AsyncExampleDelegate(int delay, string name);
        public static DateTime LongRunningMethod(int delay, string name)
        {
            TraceMsg(DateTime.Now, name + " example - thread starting.");
            Thread.Sleep(delay);
            TraceMsg(DateTime.Now, name + " example - thread stopping.");
            return DateTime.Now;
        }
        public static void BlockingExample()
        {
            AsyncExampleDelegate longRunningMethod = LongRunningMethod;
            IAsyncResult asyncResult = longRunningMethod.BeginInvoke(2000,"Blocking", null, null);
            for (int count = 0; count < 3; count++)
            {
                TraceMsg(DateTime.Now,"Continue processing until ready to block...");
                Thread.Sleep(200);
            }
            TraceMsg(DateTime.Now,"Blocking until method is complete...");
            DateTime completion = DateTime.MinValue;
            try
            {
                completion = longRunningMethod.EndInvoke(asyncResult);
            }
            catch
            {
            }

            TraceMsg(completion,"Blocking example complete.");
        }

        public static void Main()
        {
            BlockingExample();

        }
}

Result


Related Tutorials