阿宽

Nothing is more powerful than habit!
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

ADO.NET中异步处理的方式——函数回调方式

Posted on 2011-02-15 15:50  宽田  阅读(570)  评论(0编辑  收藏  举报
函数回调方式

 用代码说明

在页面上放Gridview用于显示

<body>
    
<form id="form1" runat="server">
    
<div>
        
<asp:GridView ID="gvData" runat="server">
        
</asp:GridView>
    
</div>
    
</form>
</body>

 

 

使用函数回调法方式取出数据

 

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace AdoAsyncDB
{
    
/// <summary>
    
/// 函数回调法 
    
/// </summary>
    public partial class CallBackMehtod : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            GetCallBackData();
        }

        
private void GetCallBackData()
        {
            SqlConnection DBCon;
            SqlCommand Command 
= new SqlCommand();
            IAsyncResult AsyncResult;

            DBCon 
= new SqlConnection();
            DBCon.ConnectionString 
= ConfigurationManager.ConnectionStrings["NorthWindDB"].ConnectionString;
            Command.CommandText 
= @"select top 20 companyName,contactName,city,postalCode from dbo.Customers";
            Command.CommandType 
= CommandType.Text;
            Command.Connection 
= DBCon;
            DBCon.Open();
            AsyncResult 
= Command.BeginExecuteReader(new AsyncCallback(CallBackMethod), Command);
            System.Threading.Thread.Sleep(
1000);
            DBCon.Close();
        }

        
public void CallBackMethod(IAsyncResult IResult)
        {
            SqlCommand Command 
= (SqlCommand)IResult.AsyncState;
            SqlDataReader OrdersReader 
= Command.EndExecuteReader(IResult);
            gvData.DataSource 
=
 OrdersReader;
            gvData.DataBind();
        }

    }
}