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

时间:2022-08-27 15:24:20
函数回调方式

 用代码说明

在页面上放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();
        }

    }
}