您的位置:首页 > 其它

ADO.NET2.0 异步处理的三种方式-函数回调法

2006-06-20 22:47 453 查看
下面的代码用内嵌sql语句方式通过调用BeginExecuteReader取出前五条数据,并且把callback的代理传给这个方法。不需要其他的处理,当这个异步调用结束时回调函数将被触发,并且取出结果集显示在屏幕上。

<%@ 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();

SqlAsyncResult ASyncResult;

DBCon = new SqlConnection();

Command = new SqlCommand();

DBCon.ConnectionString =

ConfigurationManager.ConnectionStrings[“DSN_NorthWind”].ConnectionString;

// Selecting top 5 records from the Orders table

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(new AsyncCallback(CBMethod),

CommandBehavior.CloseConnection);

}

public void CBMethod(SQLAsyncResult ar)

{

SqlDataReader OrdersReader;

// Retrieving result from the asynchronous process

OrdersReader = ar.EndExecuteReader(ar);

// Displaying result on the screen

gvOrders.DataSource = OrdersReader;

gvOrders.DataBind();

}

</script>

回调函数可以让你在代码的其他部分来处理命令执行的结果。这种特性在命令执行过程比一般的长但是你不想让用户等待过程调用结束时会非常有用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: