Wait方式允许只等待互相依赖的进程,然后继续执行 不相互依赖的进程。 protected void Page_Load( object sender, EventArgs e) ... { SqlCommand OrdersCommand = new SqlCommand(); SqlCommand CustCommand = new SqlCommand(); //读流 SqlDataReader OrdersReader; SqlDataReader CustReader; //声明连接 SqlConnection DBCon; //表示异步操作的状态 IAsyncResult OrdersASyncresult; IAsyncResult CustAsyncresult; //封装等待对共享资源的独占访问的操作系统特定的对象 int WHindex; System.Threading.WaitHandle[] WHandles = new System.Threading.WaitHandle[2]; System.Threading.WaitHandle OrdersWHandle; System.Threading.WaitHandle CustWHandle; //string sqlstr = ConfigurationManager.ConnectionStrings["ConnectionStrings"].ConnectionString; //连接字符串中要加入Asynchronous Processing=true 用以调用异步连接 //连接字符串中要加入MultipleActiveResultSets=true 用以调用多异步 DBCon = new SqlConnection(@"Data Source=.SQLEXPRESS;AttachDbFilename='C:Documents and Settings an桌面Hujun_tempApp_DataDatabase.mdf';Integrated Security=True;Connect Timeout=30;User Instance=True;Asynchronous Processing=true;MultipleActiveResultSets=true"); OrdersCommand = new SqlCommand("select * from hao123", DBCon); CustCommand = new SqlCommand("select * from hao123 where id=4", DBCon); DBCon.Open(); //启动异步执行,从服务器中检索一个或多个结果集 CustAsyncresult = CustCommand.BeginExecuteReader(); // 必须加入连接字符 MultipleActiveResultSets=true //否则无法调用 报“此连接不支持 MultipleActiveResultSets”的异常 OrdersASyncresult = OrdersCommand.BeginExecuteReader(); //获取用于等待异步操作完成的System.Threading.WaitHandle OrdersWHandle = OrdersASyncresult.AsyncWaitHandle; CustWHandle = CustAsyncresult.AsyncWaitHandle; //Filling Wait Handles Array with the two wait handles we are going to use in this code WHandles[0] = CustWHandle; WHandles[1] = OrdersWHandle; //Looping 2 times because there are 2 wait handles in the array for (int i = 0; i < 2; i++) ...{ // 用WaitAny 方法替代WaitAll方法。可以获得更高的效率,每个异步进程完成后 //WaitAny 方法就可以处理他们的结果,不需要等待其他进程结束 WHindex = System.Threading.WaitHandle.WaitAny(WHandles); //WHindex是获得当前的线程编号 switch (WHindex) ...{ case 0: //完成异步执行 CustReader = CustCommand.EndExecuteReader(CustAsyncresult); //绑定数据 GridView2.DataSource = CustReader; GridView2.DataBind(); break; case 1: //完成异步执行 OrdersReader = OrdersCommand.EndExecuteReader(OrdersASyncresult); //绑定数据 GridView1.DataSource = OrdersReader; GridView1.DataBind(); break; default: break; } } }