CSharp examples for Thread Asynchronous:Async
Execute a Method Asynchronously Waiting
using System;/*from w ww . java 2 s.c o m*/ 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() { AsyncExampleDelegate longRunningMethod = LongRunningMethod; IAsyncResult asyncResult = longRunningMethod.BeginInvoke(2000,"Waiting", null, null); TraceMsg(DateTime.Now, "Waiting until method is complete..."); while (!asyncResult.AsyncWaitHandle.WaitOne(300, false)) { TraceMsg(DateTime.Now, "Wait timeout..."); } DateTime completion = DateTime.MinValue; try { completion = longRunningMethod.EndInvoke(asyncResult); } catch { } TraceMsg(completion, "Waiting example complete."); } }