命名管道BeginWaitForConnection用法 [英] Named Pipes BeginWaitForConnection Usage
问题描述
我想永远不会阻止在命名管道上等待连接。那是因为,我希望我的线程能够响应超时,以及一个名为"interruptEvent"的ManualResetEvent。
所以,我看了一下使用NamePipeServerStream.BeginWaitForConnection()。文档说我必须为每次调用BeginWaitForConnection()调用一次EndWaitForConnection()。我打开连接的代码看起来像这样...
< table style ="border-top-width:0px; border-left-width:0px; margin:2px 0px; width:99%; border-bottom:#eee 0px solid; border-collapse:collapse; background-color:# fff; border-right-width:0px"cellspacing = 0 cellpadding = 0>
< tr>
差不多三年后,我遇到了同样的问题。 你认为MS现在会有一个很好的例子。 这最接近我的眼睛:
http://stackoverflow.com/questions/2700472/how-to-终止一个管理线程阻塞功能于非托管代码跨度>
I would like to NOT perpetually block waiting for a connection on a Named Pipe. That's because, I want my thread to be responsive to a timeout, and to a ManualResetEvent called "interruptEvent".
So, I looked at using NamePipeServerStream.BeginWaitForConnection(). The documentation says that I must call EndWaitForConnection() exactly once for each call to BeginWaitForConnection(). My code to open connection looks like this...
using (NamedPipeServerStream pipe = |
new NamedPipeServerStream(@"\\.\pipe\MyPipe", |
PipeDirection.InOut, |
2, |
PipeTransmissionMode.Message, |
PipeOptions.Asynchronous)) |
{ |
IAsyncResult ar = pipe.BeginWaitForConnection(null,null); |
int waitRet = WaitHandle.WaitTimeout; |
while(waitRet != 0) |
{ |
// wait up to ten seconds for the connection |
// or an interruption from the parent |
waitRet = WaitHandle.WaitAny( |
new WaitHandle [] { |
ar.AsyncWaitHandle, |
interruptEvent }, |
10000, |
false); |
switch(waitRet) |
{ |
case 0: |
// connection |
pipe.EndWaitForConnection(ar); |
break; |
case 1: case 129: |
// interruption |
// pipe.EndWaitForConnection(ar); // blocks |
return; |
case WaitHandle.WaitTimeout: |
// timeout, log something and continue |
EventLog.WriteLine("Waiting for Connection"); |
continue; |
default: |
throw new Exception("Aborted attempt to wait for client."); |
} |
} |
// read/write on with connected client |
} |
Almost three years later, I'm running up against the same issues. You'd think MS would have a good example by now. This came closest to opening my eyes:
这篇关于命名管道BeginWaitForConnection用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!