代码分析ADO.NET数据异步处理

开发 后端
这里就ADO.NET数据异步处理改善用户体验SqlCommand对象方法作出了详细的代码分析,希望大家看了会有技术上的提高。

#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"时,也可以执行同步命令,但是会损失一些资源

  1. /**/////obtainconnectionstringsfromconfigurationfilesor  
  2. ////similarfacility  
  3. ////NOTE:theseconnectionstringshavetoinclude"async=true",for  
  4. ////example:  
  5. ////"server=myserver;database=mydb;integratedsecurity=true;async=true"  
  6. //stringconnstrAccouting=GetConnString("accounting");  
  7. //stringconnstrHR=GetConnString("humanresources");  
  8. /**/////definetwoconnectionobjects,oneforeachdatabase  
  9. //using(SqlConnectionconnAcc=newSqlConnection(connstrAccounting))  
  10. //using(SqlConnectionconnHumanRes=newSqlConnection(connstrHR))  
  11. //{  
  12. ////openthefirstconnection  
  13. //connAcc.Open();  
  14. ////starttheexecutionofthefirstquerycontainedinthe  
  15. ////"employee_info"stored-procedure  
  16. //SqlCommandcmdAcc=newSqlCommand("employee_info",connAcc);  
  17. //cmdAcc.CommandType=CommandType.StoredProcedure;  
  18. //cmdAcc.Parameters.AddWithValue("@empl_id",employee_id);  
  19. //IAsyncResultarAcc=cmdAcc.BeginExecuteReader();  
  20. ////atthispoint,the"employee_info"stored-procisexecutingon  
  21. ////theserver,andthisthreadisrunningatthesametime  
  22. ////nowopenthesecondconnection  
  23. //connHumanRes.Open();  
  24. ////starttheexecutionofthesecondstored-procagainst  
  25. ////thehuman-resourcesserver  
  26. //SqlCommandcmdHumanRes=newSqlCommand("employee_hrinfo",  
  27. //connHumanRes);  
  28. //cmdHumanRes.Parameters.AddWithValue("@empl_id",employee_id);  
  29. //IAsyncResultarHumanRes=cmdHumanRes.BeginExecuteReader();  
  30. ////nowbothqueriesarerunningatthesametime  
  31. ////atthispoint;moreworkcanbedonefromthisthread,orwe  
  32. ////cansimplywaituntilbothcommandsfinish-inourcasewe'll  
  33. ////wait  
  34. //SqlDataReaderdrAcc=cmdAcc.EndExecuteReader(arAcc);  
  35. //SqlDataReaderdrHumanRes=cmdHumanRes.EndExecuteReader(arHumanRes);  
  36. ////nowwecanrendertheresults,forexample,bindthereaderstoanASP.NET  
  37. ////webcontrol,orscanthereaderanddrawtheinformationina  
  38. ////WebFormsform.  
  39. //}  
  40.  
  41. stringcustid="ALFKI";  
  42. stringorderid="10643";  
  43.  
  44. //NOTE:connectionstringsdenotedby"connstring"havetoinclude  
  45. //"async=true",forexample:  
  46. stringconnstring="server=(local);database=northwind;integratedsecurity=true;async=true";  
  47. //we'llusethreeconnectionsforthis  
  48. using(SqlConnectionc1=newSqlConnection(connstring))  
  49. using(SqlConnectionc2=newSqlConnection(connstring))  
  50. using(SqlConnectionc3=newSqlConnection(connstring))  
  51. {  
  52. //getcustomerinfo  
  53. c1.Open();  
  54. SqlCommandcmd1=newSqlCommand(  
  55. "SELECTCustomerID,CompanyName,ContactNameFROMCustomersWHERECustomerID=@id",c1);  
  56. cmd1.Parameters.Add("@id",SqlDbType.Char,5).Value=custid;  
  57. IAsyncResultarCustomer=cmd1.BeginExecuteReader();  
  58. //getorders  
  59. c2.Open();  
  60. SqlCommandcmd2=newSqlCommand("SELECT*FROMOrdersWHERECustomerID=@id",c2);  
  61. cmd2.Parameters.Add("@id",SqlDbType.Char,5).Value=custid;  
  62. IAsyncResultarOrders=cmd2.BeginExecuteReader();  
  63. //getorderdetailifuserpickedanorder  
  64. IAsyncResultarDetails=null;  
  65. SqlCommandcmd3=null;  
  66. if(null!=orderid)  
  67. {  
  68. c3.Open();  
  69. cmd3=newSqlCommand("SELECT*FROM[OrderDetails]WHEREOrderID=@id",c3);  
  70. cmd3.Parameters.Add("@id",SqlDbType.Int).Value=int.Parse(orderid);  
  71. arDetails=cmd3.BeginExecuteReader();  
  72. }  
  73. //buildthewaithandlearrayforWaitForMultipleObjects  
  74. WaitHandle[]handles=newWaitHandle[null==arDetails?2:3];  
  75. handles[0]=arCustomer.AsyncWaitHandle;  
  76. handles[1]=arOrders.AsyncWaitHandle;  
  77. if(null!=arDetails)  
  78. handles[2]=arDetails.AsyncWaitHandle;  
  79. //waitforcommandstocompleteandrenderpagecontrolsaswe  
  80. //getdataback  
  81. SqlDataReaderr;  
  82. DataTabledt;  
  83. for(intresults=(null==arDetails)?1:0;results<3;results++)  
  84. {  
  85. //waitforanyhandle,thenprocessresultsastheycome  
  86. intindex=WaitHandle.WaitAny(handles,5000,false);//5secs  
  87. if(WaitHandle.WaitTimeout==index)  
  88. thrownewException("Timeout");  
  89. switch(index)  
  90. {  
  91. case0://customerqueryisready  
  92. r=cmd1.EndExecuteReader(arCustomer);  
  93. if(!r.Read())  
  94. continue;  
  95. lblCustomerID.Text=r.GetString(0);  
  96. lblCompanyName.Text=r.GetString(1);  
  97. lblContact.Text=r.GetString(2);  
  98. r.Close();  
  99. break;  
  100. case1://ordersqueryisready  
  101. r=cmd2.EndExecuteReader(arOrders);  
  102. dt=newDataTable();  
  103. dt.Load(r);  
  104. dgOrders.DataSource=dt;//data-bindtotheordersgrid  
  105. dgOrders.Refresh();  
  106. r.Close();  
  107. break;  
  108. case2://detailsqueryisready  
  109. r=cmd3.EndExecuteReader(arDetails);  
  110. dt=newDataTable();  
  111. dt.Load(r);  
  112. dgDetails.DataSource=dt;//data-bindtothedetailsgrid  
  113. dgDetails.Refresh();  
  114. r.Close();  
  115. break;  
  116.  
  117. }  
  118. }  


以上就是ADO.NET数据异步处理用户体验的一个解决方案,大家快试试。

责任编辑:田树 来源: 博客
相关推荐

2009-10-29 11:18:47

ADO.NET SQL

2009-12-22 14:15:08

ADO.Net处理数据

2009-10-29 10:10:10

ADO.NET数据集类

2009-12-30 15:06:22

ADO.NET分析

2009-12-23 11:25:30

ADO.NET处理

2009-12-30 16:05:20

ADO.NET实例

2009-11-13 17:20:35

ADO.NET数据集工

2009-11-04 11:02:23

ADO.NET Dat

2009-11-04 13:51:46

ADO.NET性能

2009-12-31 16:09:22

ADO与ADO.NET

2009-12-23 17:50:38

ADO.NET Fra

2010-01-04 13:16:31

ADO.NET命令

2009-12-22 16:16:18

ADO.NET Deb

2010-01-04 17:27:15

ADO.NET异步操作

2009-11-13 14:22:11

ADO.NET Dat

2009-11-04 11:40:38

ADO.NET Dat

2009-12-25 14:23:35

ADO.NET设置

2009-12-21 11:29:13

Ado.Net代码

2009-12-22 09:36:29

ADO.NET代码

2009-11-04 09:02:34

ADO.NET _C
点赞
收藏

51CTO技术栈公众号