2009-05-18 56 views
13

我正在考虑为我创建的类添加一些灵活性,该类创建与远程主机的连接,然后执行信息交换(握手)。当前的实现提供了一个连接功能,它建立连接,然后阻止等待一个ManualResetEvent,直到双方完成握手。什么是IAsyncResult接口的正确实现?

这里是什么叫我的类看起来像一个例子:

// 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框架内部窥视他们如何在一些地方实现这种模式后,我觉得明智地问一下,看看是否有人成功地做到了这一点,那么需要特别关注的问题是什么?

谢谢!

回答

1

您在BCL中也有很多实现(例如, System.Runtime.Remoting.Messaging.AsyncResult) - 使用反射器或参考源将其检出。

相关问题