ADO.NET 2.0 数据异步处理改善用户体验

简介:

支持异步处理的提供程序有 System.Data.SqlClient
在针对大批量数据插入过更新时,使用异步处理方法可以不用等待多有数据更新完毕才能操作或者进行下步处理,改善了用户体验
  SqlCommand对象方法如下:
  异步方法 BeginExecuteNonQuery   EndExecuteNonQuery
           BeginExecuteXmlReader   EndExecuteXmlReader
           BeginExecuteReader   EndExecuteReader
  begin前缀的方法传入参数,end前缀的方法返回输出参数和返回值
  begin前缀方法返回的是IAsyncResult  用于追踪一步方法的执行状态
   IAsyncResult .AsnycState 用户自定义的状态对象
   IAsyncResult .AsnycWaitHandle 呼叫代码的等待形式,是等其中的一个异步方法完成还是全部完成
   IAsyncResult .CompletedSynchronously  获取所有异步方法是否同时完成
   IAsyncResult .Iscompleted 是否执行完毕,可以根据此属性进行下部动作
在连接字符串中加入"async=true"
   如果所有的命令都是同步的建议在连接字符串中显施加入"async=false"
   如果有一部分命令是异步执行,又有一部分是同步同步执行,建议分别建立两个连接对象
   如果"async=true"时,也可以执行同步命令,但是会损失一些资源
ExpandedBlockStart.gif   //// obtain connection strings from configuration files or
InBlock.gif            
//// similar facility
InBlock.gif            
//// NOTE: these connection strings have to include "async=true", for
InBlock.gif            
//// example: 
ExpandedBlockEnd.gif            
//// "server=myserver;database=mydb;integrated security=true;async=true"

None.gif              // string connstrAccouting = GetConnString("accounting");
None.gif            
// string connstrHR = GetConnString("humanresources");
ExpandedBlockStart.gif
             //// define two connection objects, one for each database
None.gif              // using (SqlConnection connAcc = new SqlConnection(connstrAccounting))
None.gif            
// using (SqlConnection connHumanRes = new SqlConnection(connstrHR))
None.gif            
// {
None.gif            
//      //  open the first connection
None.gif            
//     connAcc.Open();
None.gif            
//      //  start the execution of the first query contained in the
None.gif            
//      //  "employee_info" stored-procedure
None.gif            
//     SqlCommand cmdAcc = new SqlCommand("employee_info", connAcc);
None.gif            
//     cmdAcc.CommandType = CommandType.StoredProcedure;
None.gif            
//     cmdAcc.Parameters.AddWithValue("@empl_id", employee_id);
None.gif            
//     IAsyncResult arAcc = cmdAcc.BeginExecuteReader();
None.gif            
//      //  at this point, the "employee_info" stored-proc is executing on
None.gif            
//      //  the server, and this thread is running at the same time
None.gif            
//      //  now open the second connection
None.gif            
//     connHumanRes.Open();
None.gif            
//      //  start the execution of the second stored-proc against
None.gif            
//      //  the human-resources server
None.gif            
//     SqlCommand cmdHumanRes = new SqlCommand("employee_hrinfo",
None.gif            
//                                             connHumanRes);
None.gif            
//     cmdHumanRes.Parameters.AddWithValue("@empl_id", employee_id);
None.gif            
//     IAsyncResult arHumanRes = cmdHumanRes.BeginExecuteReader();
None.gif            
//      //  now both queries are running at the same time
None.gif            
//      //  at this point; more work can be done from this thread, or we
None.gif            
//      //  can simply wait until both commands finish - in our case we'll
None.gif            
//      //  wait
None.gif            
//     SqlDataReader drAcc = cmdAcc.EndExecuteReader(arAcc);
None.gif            
//     SqlDataReader drHumanRes = cmdHumanRes.EndExecuteReader(arHumanRes);
None.gif            
//      //  now we can render the results, for example, bind the readers to an ASP.NET
None.gif            
//      //  web control, or scan the reader and draw the information in a 
None.gif            
//      //  WebForms form.
None.gif            
// }
None.gif

None.gif            
string  custid  =   " ALFKI " ;
None.gif            
string  orderid  =   " 10643 " ;
None.gif
None.gif            
//  NOTE: connection strings denoted by "connstring" have to include 
None.gif            
//  "async=true", for example: 
None.gif
             string  connstring  =   " server=(local);database=northwind;integrated security=true;async=true " ;
None.gif            
//  we'll use three connections for this
None.gif
             using  (SqlConnection c1  =   new  SqlConnection(connstring))
None.gif            
using  (SqlConnection c2  =   new  SqlConnection(connstring))
None.gif            
using  (SqlConnection c3  =   new  SqlConnection(connstring))
ExpandedBlockStart.gif            
{
InBlock.gif                
// get customer info
InBlock.gif
                c1.Open();
InBlock.gif                SqlCommand cmd1 
= new SqlCommand(
InBlock.gif                  
"SELECT CustomerID, CompanyName, ContactName FROM Customers WHERE CustomerID=@id", c1);
InBlock.gif                cmd1.Parameters.Add(
"@id", SqlDbType.Char, 5).Value = custid;
InBlock.gif                IAsyncResult arCustomer 
= cmd1.BeginExecuteReader();
InBlock.gif                
// get orders
InBlock.gif
                c2.Open();
InBlock.gif                SqlCommand cmd2 
= new SqlCommand("SELECT * FROM Orders WHERE CustomerID=@id", c2);
InBlock.gif                cmd2.Parameters.Add(
"@id", SqlDbType.Char, 5).Value = custid;
InBlock.gif                IAsyncResult arOrders 
= cmd2.BeginExecuteReader();
InBlock.gif                
// get order detail if user picked an order
InBlock.gif
                IAsyncResult arDetails = null;
InBlock.gif                SqlCommand cmd3 
= null;
InBlock.gif                
if (null != orderid)
ExpandedSubBlockStart.gif                
{
InBlock.gif                    c3.Open();
InBlock.gif                    cmd3 
= new SqlCommand("SELECT * FROM [Order Details] WHERE OrderID=@id", c3);
InBlock.gif                    cmd3.Parameters.Add(
"@id", SqlDbType.Int).Value = int.Parse(orderid);
InBlock.gif                    arDetails 
= cmd3.BeginExecuteReader();
ExpandedSubBlockEnd.gif                }

InBlock.gif                
// build the wait handle array for WaitForMultipleObjects
InBlock.gif
                WaitHandle[] handles = new WaitHandle[null == arDetails ? 2 : 3];
InBlock.gif                handles[
0= arCustomer.AsyncWaitHandle;
InBlock.gif                handles[
1= arOrders.AsyncWaitHandle;
InBlock.gif                
if (null != arDetails)
InBlock.gif                    handles[
2= arDetails.AsyncWaitHandle;
InBlock.gif                
// wait for commands to complete and render page controls as we 
InBlock.gif                
// get data back
InBlock.gif
                SqlDataReader r;
InBlock.gif                DataTable dt;
InBlock.gif                
for (int results = (null == arDetails) ? 1 : 0; results < 3; results++)
ExpandedSubBlockStart.gif                
{
InBlock.gif                    
// wait for any handle, then process results as they come
InBlock.gif
                    int index = WaitHandle.WaitAny(handles, 5000false); // 5 secs
InBlock.gif
                    if (WaitHandle.WaitTimeout == index)
InBlock.gif                        
throw new Exception("Timeout");
InBlock.gif                    
switch (index)
ExpandedSubBlockStart.gif                    
{
InBlock.gif                        
case 0// customer query is ready
InBlock.gif
                            r = cmd1.EndExecuteReader(arCustomer);
InBlock.gif                            
if (!r.Read())
InBlock.gif                                
continue;
InBlock.gif                            lblCustomerID.Text 
= r.GetString(0);
InBlock.gif                            lblCompanyName.Text 
= r.GetString(1);
InBlock.gif                            lblContact.Text 
= r.GetString(2);
InBlock.gif                            r.Close();
InBlock.gif                            
break;
InBlock.gif                        
case 1// orders query is ready
InBlock.gif
                            r = cmd2.EndExecuteReader(arOrders);
InBlock.gif                            dt 
= new DataTable();
InBlock.gif                            dt.Load(r);
InBlock.gif                            dgOrders.DataSource 
= dt; // data-bind to the orders grid
InBlock.gif
                            dgOrders.Refresh();
InBlock.gif                            r.Close();
InBlock.gif                            
break;
InBlock.gif                        
case 2// details query is ready
InBlock.gif
                            r = cmd3.EndExecuteReader(arDetails);
InBlock.gif                            dt 
= new DataTable();
InBlock.gif                            dt.Load(r);
InBlock.gif                            dgDetails.DataSource 
= dt; // data-bind to the details grid
InBlock.gif
                            dgDetails.Refresh();
InBlock.gif                            r.Close();
InBlock.gif                            
break;
InBlock.gif
ExpandedSubBlockEnd.gif                    }

ExpandedSubBlockEnd.gif                }

ExpandedBlockEnd.gif            }



本文转自高海东博客园博客,原文链接:http://www.cnblogs.com/ghd258/archive/2005/10/30/264839.html,如需转载请自行联系原作者
相关文章
|
2月前
mvc.net分页查询案例——DLL数据访问层(HouseDLL.cs)
mvc.net分页查询案例——DLL数据访问层(HouseDLL.cs)
9 0
|
24天前
|
存储 测试技术 计算机视觉
高维数据惩罚回归方法:主成分回归PCR、岭回归、lasso、弹性网络elastic net分析基因数据
高维数据惩罚回归方法:主成分回归PCR、岭回归、lasso、弹性网络elastic net分析基因数据
|
2月前
|
SQL 数据库
使用ADO.NET查询和操作数据
使用ADO.NET查询和操作数据
12 0
|
3月前
|
SQL 开发框架 .NET
ASP.NET WEB+EntityFramework数据持久化——考核练习库——1、用户管理系统(考点:查询列表、增加、删除)
ASP.NET WEB+EntityFramework数据持久化——考核练习库——1、用户管理系统(考点:查询列表、增加、删除)
72 0
|
5月前
|
Oracle 关系型数据库 数据管理
.NET医院检验系统LIS源码,使用了oracle数据库,保证数据的隔离和安全性
LIS系统实现了实验室人力资源管理、标本管理、日常事务管理、网络管理、检验数据管理(采集、传输、处理、输出、发布)、报表管理过程的自动化,使实验室的操作人员和管理者从繁杂的手工劳作中解放出来,提高了检验人员的工作效率和效益,降低了劳动成本和差错发生率。
|
7月前
|
前端开发 JavaScript
.net core 前端传递参数有值 后端接收到的数据却是null
1、问题分析 在做接口测试时,偶然出现了前端输出有值,但是后端断点调试时却出现接收参数总是为null的情况 2、解决办法 前端打印log,看前端的每一个传值的数据类型,与后端请求参数类进行认真的一一比对 小技巧: ① 直接打印调用接口的传参值的数据类型,例如 console.log(type of this.form.name) --string console.log(type of this.form.age) --number 打印的数据类型与后端接口的参数类比对,查出不对应的类型 ② 关于非必填的值,默认传值可能出现空字符串(' ')、NaN值(Not a Number
114 0
|
8月前
|
JSON 数据格式
.NET Core - 配置绑定:使用强类型对象承载配置数据
.NET Core - 配置绑定:使用强类型对象承载配置数据
|
10月前
|
数据库 C#
C#,.net,winform导入Excel功能以及下载Excel文件到本地,并使用SqlBulkCopy把DataTable类型的数据写入到sqlserver数据库中
C#,.net,winform导入Excel功能以及下载Excel文件到本地,并使用SqlBulkCopy把DataTable类型的数据写入到sqlserver数据库中
231 0
|
12月前
|
数据采集 JavaScript 前端开发
为什么用Python爬取网页数据,在检查net work中很多和教程上不一样?
今天就来说说,我们为什么会出现这个问题,以及我们应该怎么做,才能解决这个问题?
|
Web App开发
.Net Core下使用HtmlAgilityPack解析采集互联网数据
.Net Core下使用HtmlAgilityPack解析采集互联网数据
95 0