您的位置:首页 > 其它

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

2006-06-20 22:36 309 查看
概述

开始一个异步过程,然后轮循检测异步过程返回的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方法后代码会继续执行直到异步调用结束。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: