Execute a Method Asynchronously Callback - CSharp Thread Asynchronous

CSharp examples for Thread Asynchronous:Async

Description

Execute a Method Asynchronously Callback

Demo Code


using System;/*w ww.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 CallbackHandler(IAsyncResult result)
        {
            AsyncExampleDelegate longRunningMethod =(AsyncExampleDelegate)result.AsyncState;
            DateTime completion = DateTime.MinValue;
            try
            {
                completion = longRunningMethod.EndInvoke(result);
            }
            catch
            {
            }
            TraceMsg(completion, "Callback example complete.");
        }
        public static void Main()
        {
            AsyncExampleDelegate longRunningMethod = LongRunningMethod;

            IAsyncResult asyncResult = longRunningMethod.BeginInvoke(2000,"Callback", CallbackHandler, longRunningMethod);
            for (int count = 0; count < 15; count++)
            {
                TraceMsg(DateTime.Now, "Continue processing...");
                Thread.Sleep(200);
            }

        }
}

Result


Related Tutorials