#T#很多开发语言都支持异步通信,在ADO.NET中支持异步处理的提供程序有System.Data.SqlClient在针对大批量数据插入过更新时,使用ADO.NET数据异步处理方法可以不用等待多有数据更新完毕才能操作或者进行下步处理,改善了用户体验SqlCommand对象方法如下:
ADO.NET数据异步处理
◆BeginExecuteNonQueryEndExecuteNonQuery
◆BeginExecuteXmlReaderEndExecuteXmlReader
◆BeginExecuteReaderEndExecuteReader
◆begin前缀的方法传入参数,end前缀的方法返回输出参数和返回值
◆begin前缀方法返回的是IAsyncResult用于追踪一步方法的执行状态
◆IAsyncResult.AsnycState用户自定义的状态对象
◆IAsyncResult.AsnycWaitHandle呼叫代码的等待形式,是等其中的一个异步方法完成还是全部完成
◆IAsyncResult.CompletedSynchronously获取所有异步方法是否同时完成
◆IAsyncResult.Iscompleted是否执行完毕,可以根据此属性进行下部动作
在连接字符串中加入"async=true"如果所有的命令都是同步的建议在连接字符串中显施加入,"async=false"如果有一部分命令是异步执行,又有一部分是同步同步执行,建议分别建立两个连接对象,如果"async=true"时,也可以执行同步命令,但是会损失一些资源
- /**/////obtainconnectionstringsfromconfigurationfilesor
- ////similarfacility
- ////NOTE:theseconnectionstringshavetoinclude"async=true",for
- ////example:
- ////"server=myserver;database=mydb;integratedsecurity=true;async=true"
- //stringconnstrAccouting=GetConnString("accounting");
- //stringconnstrHR=GetConnString("humanresources");
- /**/////definetwoconnectionobjects,oneforeachdatabase
- //using(SqlConnectionconnAcc=newSqlConnection(connstrAccounting))
- //using(SqlConnectionconnHumanRes=newSqlConnection(connstrHR))
- //{
- ////openthefirstconnection
- //connAcc.Open();
- ////starttheexecutionofthefirstquerycontainedinthe
- ////"employee_info"stored-procedure
- //SqlCommandcmdAcc=newSqlCommand("employee_info",connAcc);
- //cmdAcc.CommandType=CommandType.StoredProcedure;
- //cmdAcc.Parameters.AddWithValue("@empl_id",employee_id);
- //IAsyncResultarAcc=cmdAcc.BeginExecuteReader();
- ////atthispoint,the"employee_info"stored-procisexecutingon
- ////theserver,andthisthreadisrunningatthesametime
- ////nowopenthesecondconnection
- //connHumanRes.Open();
- ////starttheexecutionofthesecondstored-procagainst
- ////thehuman-resourcesserver
- //SqlCommandcmdHumanRes=newSqlCommand("employee_hrinfo",
- //connHumanRes);
- //cmdHumanRes.Parameters.AddWithValue("@empl_id",employee_id);
- //IAsyncResultarHumanRes=cmdHumanRes.BeginExecuteReader();
- ////nowbothqueriesarerunningatthesametime
- ////atthispoint;moreworkcanbedonefromthisthread,orwe
- ////cansimplywaituntilbothcommandsfinish-inourcasewe'll
- ////wait
- //SqlDataReaderdrAcc=cmdAcc.EndExecuteReader(arAcc);
- //SqlDataReaderdrHumanRes=cmdHumanRes.EndExecuteReader(arHumanRes);
- ////nowwecanrendertheresults,forexample,bindthereaderstoanASP.NET
- ////webcontrol,orscanthereaderanddrawtheinformationina
- ////WebFormsform.
- //}
- stringcustid="ALFKI";
- stringorderid="10643";
- //NOTE:connectionstringsdenotedby"connstring"havetoinclude
- //"async=true",forexample:
- stringconnstring="server=(local);database=northwind;integratedsecurity=true;async=true";
- //we'llusethreeconnectionsforthis
- using(SqlConnectionc1=newSqlConnection(connstring))
- using(SqlConnectionc2=newSqlConnection(connstring))
- using(SqlConnectionc3=newSqlConnection(connstring))
- {
- //getcustomerinfo
- c1.Open();
- SqlCommandcmd1=newSqlCommand(
- "SELECTCustomerID,CompanyName,ContactNameFROMCustomersWHERECustomerID=@id",c1);
- cmd1.Parameters.Add("@id",SqlDbType.Char,5).Value=custid;
- IAsyncResultarCustomer=cmd1.BeginExecuteReader();
- //getorders
- c2.Open();
- SqlCommandcmd2=newSqlCommand("SELECT*FROMOrdersWHERECustomerID=@id",c2);
- cmd2.Parameters.Add("@id",SqlDbType.Char,5).Value=custid;
- IAsyncResultarOrders=cmd2.BeginExecuteReader();
- //getorderdetailifuserpickedanorder
- IAsyncResultarDetails=null;
- SqlCommandcmd3=null;
- if(null!=orderid)
- {
- c3.Open();
- cmd3=newSqlCommand("SELECT*FROM[OrderDetails]WHEREOrderID=@id",c3);
- cmd3.Parameters.Add("@id",SqlDbType.Int).Value=int.Parse(orderid);
- arDetails=cmd3.BeginExecuteReader();
- }
- //buildthewaithandlearrayforWaitForMultipleObjects
- WaitHandle[]handles=newWaitHandle[null==arDetails?2:3];
- handles[0]=arCustomer.AsyncWaitHandle;
- handles[1]=arOrders.AsyncWaitHandle;
- if(null!=arDetails)
- handles[2]=arDetails.AsyncWaitHandle;
- //waitforcommandstocompleteandrenderpagecontrolsaswe
- //getdataback
- SqlDataReaderr;
- DataTabledt;
- for(intresults=(null==arDetails)?1:0;results<3;results++)
- {
- //waitforanyhandle,thenprocessresultsastheycome
- intindex=WaitHandle.WaitAny(handles,5000,false);//5secs
- if(WaitHandle.WaitTimeout==index)
- thrownewException("Timeout");
- switch(index)
- {
- case0://customerqueryisready
- r=cmd1.EndExecuteReader(arCustomer);
- if(!r.Read())
- continue;
- lblCustomerID.Text=r.GetString(0);
- lblCompanyName.Text=r.GetString(1);
- lblContact.Text=r.GetString(2);
- r.Close();
- break;
- case1://ordersqueryisready
- r=cmd2.EndExecuteReader(arOrders);
- dt=newDataTable();
- dt.Load(r);
- dgOrders.DataSource=dt;//data-bindtotheordersgrid
- dgOrders.Refresh();
- r.Close();
- break;
- case2://detailsqueryisready
- r=cmd3.EndExecuteReader(arDetails);
- dt=newDataTable();
- dt.Load(r);
- dgDetails.DataSource=dt;//data-bindtothedetailsgrid
- dgDetails.Refresh();
- r.Close();
- break;
- }
- }
- }
以上就是ADO.NET数据异步处理用户体验的一个解决方案,大家快试试。