2009-05-18 5 views
13

私は、リモートホストへの接続を確立し、情報の交換(ハンドシェイク)を実行するために作成したクラスにいくつかの柔軟性を追加しようとしています。現在の実装では、接続を確立して、2人がハンドシェイクを完了するまでManualResetEventで待機するブロックを行うConnect関数を提供しています。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) 
{ 

} 

..andここでクラスが内部的に何をするかの単純化しすぎ、高レベルのビューです:ここで

は、私のクラスを呼び出すと、どのように見えるかの例です

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
用(MS社員)
  • Googleの "たIAsyncResultの実装"

    また、BCLには多くの実装があります(例: System.Runtime.Remoting.Messaging.AsyncResult) - リフレクターまたはリファレンスソースを使用してチェックアウトします。

  • 関連する問題