【问题标题】:What is a proper implementation of the IAsyncResult interface?IAsyncResult 接口的正确实现是什么?
【发布时间】:2009-05-18 18:40:17
【问题描述】:

我正在考虑为我创建的类增加一些灵活性,该类建立与远程主机的连接,然后执行信息交换(握手)。当前实现提供了一个 Connect 函数,该函数建立连接,然后阻塞等待 ManualResetEvent 直到双方完成握手。

以下是调用我的类的示例:

// create a new client instance
ClientClass cc = new ClientClass("address of host");
bool success = cc.Connect();  // will block here until the
                              //  handshake is complete
if(success)
{

}

..这是一个过于简化的类内部工作的高级视图:

class ClientClass
{
    string _hostAddress;
    ManualResetEvent _hanshakeCompleted;
    bool _connectionSuccess;

    public ClientClass(string hostAddress)
    {
        _hostAddress = hostAddress;            
    }

    public bool Connect()
    {
        _hanshakeCompleted = new ManualResetEvent(false);            
        _connectionSuccess = false;

        // start an asynchronous operation to connect
        //  ...
        //  ...

        // then wait here for the connection and
        //  then handshake to complete
        _hanshakeCompleted.WaitOne();

        // the _connectionStatus will be TRUE only if the
        //  connection and handshake were successful
        return _connectionSuccess;
    }

    // ... other internal private methods here
    // which handle the handshaking and which call
    // HandshakeComplete at the end

    private void HandshakeComplete()
    {
        _connectionSuccess = true;
        _hanshakeCompleted.Set();
    }
}

我正在研究为此类实施.NET Classic Async Pattern。为此,我将提供 BeginConnect 和 EndConnect 函数,并允许该类的用户编写如下代码:

ClientClass cc = new ClientClass("address of host");
cc.BeginConnect(new AsyncCallback(ConnectCompleted), cc);
// continue without blocking to this line

// ..

void ConnectCompleted(IAsyncResult ar)
{
    ClientClass cc = ar.AyncState as ClientClass;
    try{
        bool success = cc.EndConnect(ar);
        if(success)
        {
             // do more stuff with the 
             //  connected Client Class object
        }
    }
    catch{
    }
}

为了能够提供这个 API,我需要创建一个实现 IAsyncResult 接口的类,该接口由 BeginConnect 函数返回,并分别传递给 EndConnect 函数。

现在,我的问题是:在类中实现 IAsyncResult 接口的正确方法是什么?

一个明显的解决方案是为 Connect 函数创建一个具有匹配签名的委托,然后使用 BeginInvoke - EndInvoke 异步调用该委托,但这不是我想要的(它不是很有效)。

我对如何做到这一点有一个粗略的想法,但是在查看了 .NET 框架内部他们如何在某些地方实现这种模式之后,我觉得询问并看看是否有人成功地做到了这一点是明智的,如果是的话有哪些问题需要特别注意。

谢谢!

【问题讨论】:

    标签: .net asynchronous design-patterns iasyncresult


    【解决方案1】:

    您可以将调用包装在 IAsyncResult 实现中。因为我最近一直在研究多线程,所以我在这里发布了它(它也有指向其他接口实现的链接):

    http://msmvps.com/blogs/luisabreu/archive/2009/06/15/multithreading-implementing-the-iasyncresult-interface.aspx

    【讨论】:

      【解决方案2】:

      您在 BCL 中也有许多实现(例如 System.Runtime.Remoting.Messaging.AsyncResult) - 使用反射器或参考源来检查它们。

      【讨论】:

        猜你喜欢
        • 2022-01-17
        • 2016-07-03
        • 2021-10-15
        • 1970-01-01
        • 2019-07-16
        • 1970-01-01
        • 2021-07-03
        • 2018-05-09
        • 1970-01-01
        相关资源
        最近更新 更多