CSharp examples for Thread Asynchronous:Async
Execute a Method Asynchronously Polling
using System;/*from w w w .j a v a2s . 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,"Polling", null, null); TraceMsg(DateTime.Now, "Poll repeatedly until method is complete."); while (!asyncResult.IsCompleted) { TraceMsg(DateTime.Now, "Polling..."); Thread.Sleep(300); } DateTime completion = DateTime.MinValue; try { completion = longRunningMethod.EndInvoke(asyncResult); } catch { } TraceMsg(completion, "Polling example complete."); } }