Execute a Method Asynchronously WaitAll - CSharp Thread Asynchronous

CSharp examples for Thread Asynchronous:Async

Description

Execute a Method Asynchronously WaitAll

Demo Code


using System;/*from w w  w  .  jav  a 2s .com*/
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 Main()
        {
            ArrayList asyncResults = new ArrayList(3);
            AsyncExampleDelegate longRunningMethod = LongRunningMethod;

            asyncResults.Add(longRunningMethod.BeginInvoke(3000,"WaitAll 1", null, null));

            asyncResults.Add(longRunningMethod.BeginInvoke(2500,"WaitAll 2", null, null));

            asyncResults.Add(longRunningMethod.BeginInvoke(1500,"WaitAll 3", null, null));
            WaitHandle[] waitHandles = new WaitHandle[3];

            for (int count = 0; count < 3; count++)
            {
                waitHandles[count] = ((IAsyncResult)asyncResults[count]).AsyncWaitHandle;
            }
            TraceMsg(DateTime.Now, "Waiting until all 3 methods are complete...");

            while (!WaitHandle.WaitAll(waitHandles, 300, false))
            {
                TraceMsg(DateTime.Now, "WaitAll timeout...");
            }

            DateTime completion = DateTime.MinValue;

            foreach (IAsyncResult result in asyncResults)
            {
                try
                {
                    DateTime time = longRunningMethod.EndInvoke(result);
                    if (time > completion) completion = time;
                }
                catch
                {
                    // Catch and handle those exceptions you would if calling
                    // LongRunningMethod directly.
                }
            }

            // Display completion information
            TraceMsg(completion, "WaitAll example complete.");

        }
}

Result


Related Tutorials