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

下面的代码用内嵌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>

回调函数可以让你在代码的其他部分来处理命令执行的结果。这种特性在命令执行过程比一般的长但是你不想让用户等待过程调用结束时会非常有用。

 

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

评论

#1楼  2007-03-20 21:34 laudy [未注册用户]

这段程序能运行吗?(就算是不考虑连接字符串等问题)

请问:SqlAsyncResult类是哪个命名空间中的?应该是IAsyncResult吧?

我试了一下你的这段程序,可得不到数据(显示不出GRID VIEW来),但程序调试的时候没有任何问题,单步执行也按照我所想的执行下去的,不过我用不了SqlAsyncResult(提示没有引用?),必须换成IAsyncResult。   回复  引用    

#2楼  2007-03-21 22:41 zhanqiangz(闲云野鹤) [未注册用户]

◎laudy
我只是按照professional asp.net2.0翻译的,不过看顶部导入的名称空间应该是在System.Data.SqlClient里。   回复  引用    

#3楼  2007-10-15 21:42 oyjd614 [未注册用户]

这段函数有问题,特别版也没有修改这一问题,真是让我对红皮书有点失望了。正确的应该是:
AsyncCallback Callback = new AsyncCallback(CallBackMethod);
SupIsynResult = SupCmd.BeginExecuteReader(Callback,SupCmd);
System.Threading.Thread.Sleep(100);
MyCon.Dispose();
public void CallBackMethod(IAsyncResult IResult)
{
SqlCommand Command = (SqlCommand)IResult.AsyncState;
SqlDataReader dr = Command.EndExecuteReader(IResult);

GridView1.DataSource = dr;
GridView1.DataBind();
}   回复  引用    


标题  
姓名  
主页
Email (只有博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      
该文被作者在 2006-06-20 22:59 编辑过
 
另存  打印
 


<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

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜