ADO.NET2.0 异步处理的三种方式-轮循检测法

概述

开始一个异步过程,然后轮循检测异步过程返回的IAsyncResult对象来判断过程调用是否结束。

为异步过程提供一个回调函数。这种方法可以让你并行处理其他的任务。当异步过程结束时,回调函数被 触发用来处理过程结束后的清理工作以及通知程序的其他部分该异步过程已经结束。

第三种方法使用wait handle来处理异步过程,这是三种方法中最优雅的方法。使用这种方法你可以开启你想开启的所有异步过程,然后等待其中任何或者全部过程结束以便于做对应的处理。

 

轮循检测法

 

下面的代码用内嵌sql语句的办法取出Northwind数据库中Orders表中的前五条数据。可以通过调用BeginExecuteReader来开始一个异步过程,接下来用一个循环来等到过程结束。在等待的时候主线程会每休眠10毫秒后检测异步过程返回的结果来判断过程调用是否结束。当过程结束时用EndExecuteReader来返回结果集。

 

C#

<%@ Page Language=C# %>

<%@ Import Namespace=System.Data %>

<%@ Import Namespace=System.Data.SqlClient %>

<%@ Import Namespace=System.Configuration %>

<script runat=server>

protected void Page_Load(object sender, EventArgs e)

{

SqlConnection DBCon;

SqlCommand Command = new SqlCommand();

SqlDataReader OrdersReader;

IAsyncResult ASyncResult;

DBCon = new SqlConnection();

DBCon.ConnectionString =

ConfigurationManager.ConnectionStrings[DSN_NorthWind].ConnectionString;

Command.CommandText =

SELECT TOP 5 Customers.CompanyName, Customers.ContactName, +

Orders.OrderID, Orders.OrderDate, +

Orders.RequiredDate, Orders.ShippedDate +

FROM Orders, Customers +

WHERE Orders.CustomerID = Customers.CustomerID +

ORDER BY Customers.CompanyName, Customers.ContactName

Command.CommandType = CommandType.Text;

Command.Connection = DBCon;

DBCon.Open();

// Starting the asynchronous processing

ASyncResult = Command.BeginExecuteReader();

// This loop with keep the main thread waiting until the

// asynchronous process is finished

while (!ASyncResult.IsCompleted)

{

// Sleeping current thread for 10 milliseconds

System.Threading.Thread.Sleep(10);

}

// Retrieving result from the asynchronous process

OrdersReader = Command.EndExecuteReader(ASyncResult);

// Displaying result on the screen

gvOrders.DataSource = OrdersReader;

gvOrders.DataBind();

// Closing connection

DBCon.Close();

}

</script>

如果你在while循环中打个断点,你会发现调用BeginExecuteReader方法后代码会继续执行直到异步调用结束。

posted on 2006-06-20 22:36 zhanqiangz(闲云野鹤) 阅读(886) 评论(0)  编辑 收藏 所属分类: 翻译


标题  
姓名  
主页
Email (博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
博客园首页

新闻频道

社区

小组

博问

网摘

闪存

  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      
该文被作者在 2006-06-20 22:54 编辑过
成果网帮您增加网站收入


相关链接:
 


<2006年6月>
28293031123
45678910
11121314151617
18192021222324
2526272829301
2345678

导航

统计

公告

如转载本博客的相关资料敬请注明出处.谢谢合作!

与我联系

搜索

 

常用链接

留言簿(6)

我参与的团队

我的标签

随笔分类(51)

随笔档案(49)

文章分类(7)

文章档案(5)

收藏夹(3)

.NET

BizTalk

Design

JavaScript

My Blogs

Power Tools

Process Control

Search Engine

SQL Server

XML

积分与排名

最新评论

阅读排行榜

评论排行榜