我正在考慮爲我創建的類添加一些靈活性,該類創建與遠程主機的連接,然後執行信息交換(握手)。當前的實現提供了一個連接功能,它建立連接,然後阻止等待一個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框架內部窺視他們如何在一些地方實現這種模式後,我覺得明智地問一下,看看是否有人成功地做到了這一點,那麼需要特別關注的問題是什麼?
謝謝!