2

我正在尝试在异步 WCF 方法中使用 ADO.Net 的 BeginExecuteReader 方法,但无法获得它。

我有以下合同和服务代码。我不明白如何在服务的开始方法中填写回调方法的详细信息。任何帮助将不胜感激,因为我在网上找不到任何示例或 MSDN 上的任何文档。甚至一些指向示例代码的链接也会有所帮助,因为我完全不知道如何做到这一点。

合约代码:

    [ServiceContract(Namespace = ServiceConstants.ServiceContractNamespace,
    Name = ServiceConstants.ServiceName)]
    public interface IAsyncOrderService
    {
       [OperationContract(AsyncPattern=true)]
       IAsyncResult BeginGetProducts(string vendorId, AsyncCallback callback,
                                                object state);

       List<Product> EndGetProducts(IAsyncResult result);
    }

服务代码为:

    public IAsyncResult BeginGetProducts(string vendorId, AsyncCallback cb, object s)
    {
        DocumentsSummaryByProgram summary = null;

        SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Conn1"].ConnectionString);
        SqlCommand sqlCmd = null;


        sqlCmd = new SqlCommand("dbo.GetProducts", conn);
        sqlCmd.CommandType = CommandType.StoredProcedure;

        sqlCmd.Parameters.AddWithValue("@vendorId", sqlCmd);

        conn.Open();

        return sqlCmd.BeginExecuteReader(cb, vendorId);
    }

    public List<Product> EndGetProducts(IAsyncResult r)
    {
        List<Product> products = new List<Product>();
        SqlCommand cmd = r.AsyncState as SqlCommand;
        if (cmd != null)
        {
            SqlDataReader dr = cmd.EndExecuteReader(r);
            while (dr.Read())
            {
                //do your processing here and populate products collection object
            }
        }

        return products;
    }

更新 1:似乎是一项不可能完成的任务。Microsoft 应该提供示例来展示如何以异步方式从 WCF 调用 ADO.Net 异步方法,因为这对于许多想要可扩展的应用程序很有用。

更新 2:在我能够在 WCF 中成功实现异步模式之后,我已经为我的问题提供了详细的答案。请在下面的单独帖子中查看答案。

4

2 回答 2

3

你从来没有打电话打开你的SqlConnection

conn.Open();

您还创建了两个SqlConnection对象:

SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Conn1"].ConnectionString);

和:

sqlCmd = new SqlCommand("dbo.GetProducts", new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["VHA_EDM"].ConnectionString));

编辑

要添加异步回调,您将执行以下操作:

var callback = new AsyncCallback(HandleCallback);
sqlCmd.BeginExecuteReader(callback, command);

如果您没有计划在两者之间运行的任何异步代码,那么BeginExecuteReader最好EndExecuteReader只使用ExecuteReader.

编辑 2

委托人具有以下AsyncCallback签名:

public delegate void AsyncCallback(IAsyncResult ar);

从该委托方法中,您可以使用Invoke您的EndGetProducts方法。

编辑 3

以下是使用检索数据的示例BeginExecuteReader

public SqlCommand Command { get; set; }

public IAsyncResult BeginGetStuff()
{
    var connect = "[enter your connection string here]";
    // Note: Your connection string will need to contain:
    // Asynchronous Processing=true;

    var cn = new SqlConnection(connect);
    cn.Open();

    var cmd = new SqlCommand("[enter your stored proc name here]", cn);
    cmd.CommandType = CommandType.StoredProcedure;
    this.Command = cmd;

    return cmd.BeginExecuteReader();
}

public List<string> EndGetStuff(IAsyncResult r)
{
    var dr = this.Command.EndExecuteReader(r);
    var list = new List<string>();
    while (dr.Read())
        list.Add(dr[0].ToString());
    return list;
}
于 2012-12-24T01:05:08.893 回答
1

我提供了一个单独的帖子来回答我的问题,因为这是一个很长的答案。我希望它可以帮助其他人在他们的 WCF 中快速实现异步模式。在 WCF 中实现异步模式时我遗漏的要点如下。没有这些,我要么收到一个挂起的 WCF 问题,说“正​​在连接...”,要么在 WCF 级别操作被中止/取消错误消息。在下面的解决方案中,我没有讨论 WCF 端异步模式中的异常处理以保持简单。

  • 不要通过代码调用 WCF 的 EndGetProducts 方法,例如使用 delagateInstance.Invoke 或任何其他方式调用它。在异步模式中,您需要做的就是调用客户端回调,当您的长异步操作完成时,这将导致调用您的客户端回调,然后调用 WCF EndGetProduct 方法(例如:cb( asyncResult1) 其中 cb 是调用此 WCF 的客户端代码传递的回调委托实例)。我试图通过使用 Invoke 来调用 EndGetProducts WCF 方法,这是错误的。即使客户端没有为客户端回调传递任何内容,仍应执行此操作以调用 WCF 中的 End 方法。
  • 不要返回从 ADO.Net async begindatareader 方法和 BeginGetProducts 方法获得的 asyncresult,因为它需要与客户端调用 WCF 的上下文中的 AsyncResult 相同。这意味着您必须在 BeginGetProducts 将返回的 AsyncResult 中包含客户端回调和客户端状态对象,即使客户端没有为这些传递任何内容。我从 BeginGetProducts 返回 ADO.Net 异步方法 begindatareader 的 AsyncResult,这是错误的。
  • 从 WCF 调用客户端回调委托实例时,请确保传递包含我在上一个项目符号中讨论的客户端上下文的 AsyncResult。此外,当您的异步操作完成时执行此操作,我在创建 List 对象后的 beginexecutereader 回调中执行此操作。
  • 要记住的最后一点是,您必须在 WCF 和 ADO.Net 级别设置足够大的超时,因为您的异步操作可能需要相当长的时间,否则您将在 WCF 中获得超时。为此,将 ADO.Net 命令超时设置为 0(无限超时)或适当的值,对于 WCF,您可以包括如下配置。

    <binding name="legacyBinding" openTimeout="00:10:00" sendTimeout="00:10:00"    
    receiveTimeout="00:10:00" closeTimeout="00:10:00"  maxBufferPoolSize="2147483647" 
    maxReceivedMessageSize="2147483647" >
    

现在的代码可能看起来很长,但我的目的是让其他人更容易在他们的 WCF 中实现异步模式。这对我来说相当困难。

WCF 合同

    [OperationContract(AsyncPattern = true)]
    [FaultContract(typeof(string))]
    IAsyncResult BeginGetProducts(string vendorId, AsyncCallback cb, object s);
    //The End method must return the actual datatype you intend to return from 
    //your async WCF operation. Also, do not decorate the End method with 
    //OperationContract or any other attribute
    List<Product> EndGetProducts(IAsyncResult r);

WCF 实施

       public IAsyncResult BeginGetProducts( string vendorId, AsyncCallback cb, object s)
    {

        SqlCommand sqlCmd = null;
        sqlCmd = new SqlCommand("dbo.ABC_sp_GetProducts", "Data Source=xyz;Initial Catalog=NorthwindNew;Integrated Security:true;asynchronous processing=true;"));
        sqlCmd.CommandType = CommandType.StoredProcedure;
        sqlCmd.Parameters.AddWithValue("@vendorId", vendorId);
        sqlCmd.CommandTimeout = 0;//async operations can be long operations so set a long timeout

        //THIS ASYNRESULT MUST REFLECT THE CLIENT-SIDE STATE OBJECT, AND IT IS WHAT SHOULD FLOW THROUGH TO END METHOD of WCF.
        //THE CLIENT CALLBACK (PARAMETER 'cb') SHOULD BE INVOKED USING THIS ASYNCRESULT, ELSE YOUR WCH WILL HANG OR YOUR WCF WILL GET ABORTED AUTOMATICALLY.
        AsyncResult<FinalDataForDocumentsSummary> asyncResult1 = new AsyncResult<FinalDataForDocumentsSummary>(false, s);//this is the AsyncResult that should be used for any WCF-related method (not ADO.Net related)

        AsyncCallback callback = new AsyncCallback(HandleCallback);//this is callback for ADO.Net async begindatareader  method


        sqlCmd.Connection.Open();

        //AsynResult below is for passing information to ADO.Net asyn callback
        AsyncResult<Product> cmdResult = new AsyncResult<Product>(false, new object[] {sqlCmd, cb,s});

        sqlCmd.BeginExecuteReader(HandleCallback, cmdResult);


         return asyncResult1;//ALWAYS RETURN THE ASYNCRESULT INSTANTIATED FROM CLIENT PARAMETER OF STATE OBJECT. FOR DATAREADER CREATE ANOTHER ASYNCRESULT THAT HAS COMMAND OBJECT INSIDE IT.
    }


     /// <summary>
     /// This is the callback on WCF side for begin data reader method.
     /// This is where you retrieve data, and put it into appropriate data objects to be returned to client.
     /// Once data has been put into these objects, mark this ASYNC operation as complete and invoke the
    ///  client callback by using 'cb(asyncResult1)'. Use the same asyncresult that contains the client passed state object.
     /// </summary>
     /// <param name="result"></param>
    public void HandleCallback(IAsyncResult result)
    {
        List<Product> summaries = new List<Product>();
        Product product = null;

        //THIS ASYNCRESULT IS ONLY FOR DATAREADER ASYNC METHOD AND NOT TO BE USED WITH WCF, ELSE BE READY FOR WCF FAILING
        AsyncResult<Product> asyncResult = result.AsyncState as AsyncResult<Product>;

        object[] objects = asyncResult.AsyncState as object[];
        SqlCommand cmd = objects[0] as SqlCommand;
        AsyncCallback cb = objects[1] as AsyncCallback;
        object s = objects[2];
       //CREATE THE SAME ASYNCRESULT THAT WE HAD IN BEGIN METHOD THAT USES THE CLIENT PASSED STATE OBJECT
        AsyncResult<Product> asyncResult1 = new AsyncResult<Product>(false, s);


        SqlDataReader dr = null;
        if (cmd != null)
        {
            try
            {
                  dr = cmd.EndExecuteReader(result);
                while (dr.Read())
                {
                    product = new Product(dr.GetInt32(0), dr.GetString(1));
                    summaries.Add(summary);
                }


                dr.Close();
                cmd.Connection.Close();

                //USE THE CORRECT ASYNCRESULT. WE NEED THE ASYNCRESULT THAT WE CREATED IN BEGIN METHOD OF WCF.
                asyncResult1.Data = new FinalDataForDocumentsSummary(count, summaries.OrderByDescending(x => x.CountOfOverDue).ToList());

            }
            finally
            {
                if (dr != null)
                {
                    dr.Close();
                }
                if (cmd.Connection != null)
                {
                    cmd.Connection.Close();
                    cmd.Connection.Dispose();
                }

                //USE THE CORRECT ASYNCRESULT. WE NEED THE ASYNCRESULT THAT WE CREATED IN BEGIN METHOD OF WCF
                asyncResult1.Complete();

                //THIS IS REQUIRED ELSE WCF WILL HANG. EVEN WHEN NO CALLBACK IS PASSED BY CLIENT,
                //YOU MUST EXECUTE THIS CODE. EXECUTE IT AFTER YOUR OPERATION HAS COMPLETED, 
                //SINCE THIS IS WHAT CAUSES THE END METHOD IN WCF TO EXECUTE. 
                //DON'T TRY TO CALL THE WCF END METHOD BY YOUR CODE (like using delegateInstance.Invoke) SINCE THIS WILL HANDLE IT.
                cb(asyncResult1);

            }
        }


    }
    /// <summary>
    /// This method gets automatically called by WCF if you include 'cb(asyncResult1)' in the reader's callback meethod, so don't try to call it by your code. 
    /// But always use 'cb(asyncResult1)' just after data has been successfully retrieved from database and operation is marked as complete.
    /// </summary>
    /// <param name="r"></param>
    /// <returns></returns>
    public List<Product> EndGetProducts(IAsyncResult r)
    {

       AsyncResult<Product> result = r as AsyncResult<Product>;


       // Wait until the AsyncResult object indicates the 
       // operation is complete, in case the client called the End method just after the Begin method.
        if (!result.CompletedSynchronously)
        {
            System.Threading.WaitHandle waitHandle = result.AsyncWaitHandle;
            waitHandle.WaitOne();
        }

        // Return the database query results in the Data field
        return result.Data;

    }

异步模式中需要的 AsyncResult 的泛型类

using System;
using System.Threading;


class AsyncResult<T> : IAsyncResult
{
    private T data;
    private object state;
    private bool isCompleted = false;
    private AutoResetEvent waitHandle;
    private bool isSynchronous = false;

    public T Data
    {
        set { data = value; }
        get { return data; }
    }

    public AsyncResult(bool synchronous, object stateData)
    {
        isSynchronous = synchronous;
        state = stateData;
    }

    public void Complete()
    {
        isCompleted = true;
        ((AutoResetEvent)AsyncWaitHandle).Set();
    }

    public object AsyncState
    {
        get { return state; }
    }

    public WaitHandle AsyncWaitHandle
    {
        get
        {
            if (waitHandle == null)
                waitHandle = new AutoResetEvent(false);

            return waitHandle;
        }
    }

    public bool CompletedSynchronously
    {
        get
        {
            if (!isCompleted)
                return false;
            else
                return isSynchronous;
        }
    }

    public bool IsCompleted
    {
        get { return isCompleted; }
    }
}

如何从客户端调用它:

    protected void Page_Load(object sender, EventArgs e)
    {
        using (ABCService.ServiceClient sc = new ABCService.ServiceClient())
        {
           // List<ABCService.Product> products = sc.GetDocSummary("Vend1", null, false);//this is synchronous call from client
          sc.BeginGetProducts("Vend1",GetProductsCallback, sc);//this is asynchronous call from WCF

        }

    }

    protected void GetProductsCallback(IAsyncResult asyncResult)
    {
        List<ABCService.Product> products = ((ABCService.ServiceClient)asyncResult.AsyncState).EndGetProducts(asyncResult);//this will call the WCF EndGetProducts method

    }
于 2012-12-25T19:08:56.210 回答