我需要找到一種方式,當以異步模式打開的System.IO.Pipe.NamedPipeServerStream具有更多可讀取的數據時 - WaitHandle將是理想的。我不能簡單地使用BeginRead()來獲得這樣的句柄,因爲可能會由另一個想要寫入管道的線程發出信號 - 所以我必須釋放管道上的鎖並等待寫入完成,和NamedPipeServerStream沒有一個CancelAsync方法。我也嘗試調用BeginRead(),然後在管道上調用win32函數CancelIO,但是我不認爲這是一個理想的解決方案,因爲如果在數據到達並正在處理的情況下調用CancelIO,它將會被丟棄 - 我仍然希望保留這些數據,但是在寫完後稍後再進行處理。我懷疑win32函數PeekNamedPipe可能是有用的,但我想避免不得不連續輪詢新數據。命名管道 - 異步查看
在likley倘上述文字是有點不清楚,這裏的大致我想怎麼能夠做到?
NamedPipeServerStream pipe;
ManualResetEvent WriteFlag;
//initialise pipe
lock (pipe)
{
//I wish this method existed
WaitHandle NewDataHandle = pipe.GetDataAvailableWaithandle();
Waithandle[] BreakConditions = new Waithandle[2];
BreakConditions[0] = NewDataHandle;
BreakConditions[1] = WriteFlag;
int breakcode = WaitHandle.WaitAny(BreakConditions);
switch (breakcode)
{
case 0:
//do a read on the pipe
break;
case 1:
//break so that we release the lock on the pipe
break;
}
}
+1:使用帶有重疊I/O的0字節讀取作爲接收數據時未實際讀取任何數據的信號的方式非常有用,並且在文檔中沒有顯而易見。 – 2010-09-18 23:16:43