异步调用的四种方式 using System; using System.Threading; namespace ThreadDemo ... { public class YibuSelf ...{ public delegate void MyDelegate(); public static MyDelegate dele; public static void Main() ...{ 同步方式#region 同步方式 // Test(); #endregion dele = new MyDelegate( Test ); 回调方式#region 回调方式 IAsyncResult ar = dele.BeginInvoke(new AsyncCallback( MyCallback ), null); #endregion 轮询方式#region 轮询方式// IAsyncResult ar = dele.BeginInvoke( null,null); // while( !ar.IsCompleted ) // { // Thread.Sleep(100); // Console.Write("."); // } // Console.WriteLine(); // Console.WriteLine("异步操作结束."); #endregion 调用End方法#region 调用End方法 // IAsyncResult ar = dele.BeginInvoke( null,null); // dele.EndInvoke( ar ); // Console.WriteLine("异步操作结束."); #endregion WaitHandle#region WaitHandle// IAsyncResult ar = dele.BeginInvoke( null,null);// ar.AsyncWaitHandle.WaitOne();// dele.EndInvoke( ar );// Console.WriteLine("异步操作结束."); #endregion // 执行线程中其他内容 Console.WriteLine("线程的其余部分执行"); Console.Read(); } public static void Test() ...{ for( int i=0; i<10; i++) ...{ Console.Write("+"); Thread.Sleep(200); } } public static void MyCallback( IAsyncResult ar ) ...{ dele.EndInvoke( ar ); Console.WriteLine(); Console.WriteLine("异步操作结束."); } }} 在多线程环境中保护状态和数据 using System; using System.Threading; using System.Runtime.Remoting.Contexts; using System.Runtime.CompilerServices; namespace ThreadDemo ... { //[Synchronization] public class Synch_Example : ContextBoundObject ...{ static int sCount = 0; // 静态字段 int iCount = 0; // 实例字段 // 同一时刻只有一个线程可以执行实例方法 事例方法#region 事例方法 public void Add() ...{ // lock( this ) //Monitor.Enter( this );Monitor.Exit( this ); Console.WriteLine("Start add count,static:{0},instance:{1}", sCount, this.iCount); int tempS = sCount; int tempI = this.iCount; Thread.Sleep(50); tempS++; tempI++; sCount = tempS; this.iCount = tempI; Console.WriteLine(" End add count,static:{0},instance:{1}", sCount, this.iCount); } #endregion 静态方法#region 静态方法 //[MethodImpl( MethodImplOptions.Synchronized )] public static void Hello() ...{ //lock( typeof( Synch_Example ) ) Console.Write("Hello "); Thread.Sleep(50); Console.Write("World"); Thread.Sleep(50); Console.Write("!"); Console.WriteLine(); } #endregion } class Example_Synch ...{ public static void Main() ...{ Synch_Example se1 = new Synch_Example(); 实例方法线程#region 实例方法线程 Thread t1 = new Thread( new ThreadStart( se1.Add )); Thread t2 = new Thread( new ThreadStart( se1.Add )); Thread t3 = new Thread( new ThreadStart( se1.Add )); Thread t4 = new Thread( new ThreadStart( se1.Add )); t1.Start(); t2.Start(); t3.Start(); t4.Start(); #endregion Thread.Sleep( 1000 ); 静态方法线程#region 静态方法线程 Thread t5 = new Thread( new ThreadStart( Synch_Example.Hello )); Thread t6 = new Thread( new ThreadStart( Synch_Example.Hello )); Thread t7 = new Thread( new ThreadStart( Synch_Example.Hello )); Thread t8 = new Thread( new ThreadStart( Synch_Example.Hello )); t5.Start(); t6.Start(); t7.Start(); t8.Start(); #endregion Console.Read(); } }}