阿宽

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

ADO.NET中异步处理的方式——Wait方式

Posted on 2011-02-15 15:46  宽田  阅读(1334)  评论(0编辑  收藏  举报
Wait方式使用方法
      三种方式中最好的一种不是Poll方式,也不是回调方式,而是Wait方式。该方式提供的灵活性最大、效率最高,但有点复杂。使用这种方式,可以编写代码,启动多个异步进程,等待全部或部分进程的完成。这种方式允许只等待互相依赖的进程,然后继续执行不互相依赖的进程。按照其设计,这种方式需要仔细考虑异步进程。必须认真选择出以并行方式运行的异步进程,最重要的是,确定不同的进程如何相互依赖。这种方式的复杂性在于,需要理解其中的细节,并设计出相应的代码。最终结果一般是,非常简洁的代码设计能最大限度地利用同步和异步处理模型。

 

用代码说明。

 

 在页面上放两个Gridview用于显示数据。

代码
<body>
    
<form id="form1" runat="server">
    
<div>
        
<asp:GridView ID="gvOrders" runat="server" AutoGenerateColumns="false">
            
<Columns>
                
<asp:BoundField HeaderText="Comany Name" DataField="CompanyName" />
                
<asp:BoundField HeaderText="Contact Name" DataField="ContactName" />
                
<asp:BoundField HeaderText="Contact Title" DataField="ContactTitle" />
                
<asp:BoundField HeaderText="Order Date" DataField="OrderDate" DataFormatString="{0:d}" />
            
</Columns>
        
</asp:GridView>
    
</div>
    
<br />
    
<div>
        
<asp:GridView ID="gvCustomers" runat="server">
        
</asp:GridView>
    
</div>
    
</form>
</body>


 使用Wait方式取出数据

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

namespace AdoAsyncDB
{
    
/// <summary>
    
/// 使用Wait方式
    
/// </summary>
    public partial class WaitMethod : System.Web.UI.Page
    {

        
protected void Page_Load(object sender, EventArgs e)
        {
            GetWaitAnyData();
        }

        
/// <summary>
        
/// 使用Wait方式
        
/// 等待句柄关联到异步进程上。使此这种方式,可以启动需要的所有异步进程,等待全部或部分进程的完成,以便对它们执行相应的处理。
        
/// 使用这种方式,可以编写代码,启动多个异步进程,等待全部或部分进程的完成。这个方式允许只等待互相依赖的进程,然后继续执行不互相依赖的进程。
        
/// </summary>
        private void GetWaitData()
        {
            SqlConnection DBCon;
            SqlCommand Command 
= new SqlCommand();
            SqlDataReader OrdersReader;
            IAsyncResult AsyncResult;
            System.Threading.WaitHandle WHandle;

            DBCon 
= new SqlConnection();
            DBCon.ConnectionString 
= ConfigurationManager.ConnectionStrings["NorthWindDB"].ConnectionString;
            Command.CommandText 
= @"select top 50 Customers.CompanyName,Customers.ContactName,customers.ContactTitle,
                            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();
            AsyncResult 
= Command.BeginExecuteReader();

            WHandle 
= AsyncResult.AsyncWaitHandle;

            
if (WHandle.WaitOne() == true)
            {
                OrdersReader 
= Command.EndExecuteReader(AsyncResult);
                gvOrders.DataSource 
= OrdersReader;
                gvOrders.DataBind();
                DBCon.Close();
            }
            
else
            {
                
//Asynchronous process has time out.Handle this situation here.
            }
        }

        
/// <summary>
        
/// 使用多个等待句柄,等待全部
        
/// </summary>
        private void GetWaitAllData()
        {
            SqlConnection DBCon;
            SqlCommand OrdersCommand 
= new SqlCommand();
            SqlCommand CustCommand 
= new SqlCommand();
            SqlDataReader OrdersReader;
            SqlDataReader CustReader;
            IAsyncResult OrdersAsyncResult;
            IAsyncResult CustAsyncResult;

            System.Threading.WaitHandle[] WHandles 
= new System.Threading.WaitHandle[2];
            System.Threading.WaitHandle OrdersWHandle;
            System.Threading.WaitHandle CustWHandle;


            DBCon 
= new SqlConnection();
            DBCon.ConnectionString 
= ConfigurationManager.ConnectionStrings["NorthWindDB"].ConnectionString;

            CustCommand.CommandText 
= "select * from customers where companyName='Alfreds Futterkiste'";
            CustCommand.CommandType 
= CommandType.Text;
            CustCommand.Connection 
= DBCon;


            OrdersCommand.CommandText 
= @"select top 50 Customers.CompanyName,Customers.ContactName,customers.ContactTitle,
                            orders.OrderID,Orders.OrderDate,Orders.RequiredDate,orders.ShippedDate
                            from Orders,Customers
                            where Orders.CustomerID=customers.CustomerID
                            order by customers.CompanyName,customers.ContactName
";
            OrdersCommand.CommandType 
= CommandType.Text;
            OrdersCommand.Connection 
= DBCon;

            DBCon.Open();

            CustAsyncResult 
= CustCommand.BeginExecuteReader();
            OrdersAsyncResult 
= OrdersCommand.BeginExecuteReader();

            CustWHandle 
= CustAsyncResult.AsyncWaitHandle;
            OrdersWHandle 
=
 OrdersAsyncResult.AsyncWaitHandle;

            WHandles[
0= CustWHandle;
            WHandles[
1= OrdersWHandle;

            System.Threading.WaitHandle.WaitAll(WHandles);

            CustReader 
= CustCommand.EndExecuteReader(CustAsyncResult);
            OrdersReader 
=
 OrdersCommand.EndExecuteReader(OrdersAsyncResult);

            gvCustomers.DataSource 
= CustReader;
            gvCustomers.DataBind();

            gvOrders.DataSource 
= OrdersReader;
            gvOrders.DataBind();

            DBCon.Close();
        }


        
/// <summary>
        
/// 使用多个等待句柄,等待部分
        
/// </summary>
        private void GetWaitAnyData()
        {
            SqlConnection DBCon;
            SqlCommand OrdersCommand 
= new SqlCommand();
            SqlCommand CustCommand 
= new SqlCommand();
            SqlDataReader OrdersReader;
            SqlDataReader CustReader;
            IAsyncResult OrdersAsyncResult;
            IAsyncResult CustAsyncResult;

            
int WHindex;
            System.Threading.WaitHandle[] WHandles 
= new System.Threading.WaitHandle[2];
            System.Threading.WaitHandle OrdersWHandle;
            System.Threading.WaitHandle CustWHandle;


            DBCon 
= new SqlConnection();
            DBCon.ConnectionString 
= ConfigurationManager.ConnectionStrings["NorthWindDB"].ConnectionString;

            CustCommand.CommandText 
= "select * from customers where companyName='Alfreds Futterkiste'";
            CustCommand.CommandType 
= CommandType.Text;
            CustCommand.Connection 
= DBCon;


            OrdersCommand.CommandText 
= @"select top 5 Customers.CompanyName,Customers.ContactName,customers.ContactTitle,
                            orders.OrderID,Orders.OrderDate,Orders.RequiredDate,orders.ShippedDate
                            from Orders,Customers
                            where Orders.CustomerID=customers.CustomerID
                            order by customers.CompanyName,customers.ContactName
";
            OrdersCommand.CommandType 
= CommandType.Text;
            OrdersCommand.Connection 
= DBCon;

            DBCon.Open();

            CustAsyncResult 
= CustCommand.BeginExecuteReader();
            OrdersAsyncResult 
= OrdersCommand.BeginExecuteReader();

            CustWHandle 
= CustAsyncResult.AsyncWaitHandle;
            OrdersWHandle 
= OrdersAsyncResult.AsyncWaitHandle;

            WHandles[
0= CustWHandle;
            WHandles[
1= OrdersWHandle;


            
for (int Index = 0; Index < 2; Index++)
            {
                WHindex 
= System.Threading.WaitHandle.WaitAny(WHandles);
                
switch (WHindex)
                {
                    
case 0:
                        CustReader 
= CustCommand.EndExecuteReader(CustAsyncResult);
                        gvCustomers.DataSource 
= CustReader;
                        gvCustomers.DataBind();
                        
break;
                    
case 1:
                        OrdersReader 
= OrdersCommand.EndExecuteReader(OrdersAsyncResult);
                        gvOrders.DataSource 
= OrdersReader;
                        gvOrders.DataBind();
                        
break;
                    
default:
                        
break
;
                }
            }

            DBCon.Close();
        }
    }
}