为什么我的NamedPipeServerStream不会等待?

时间:2010-04-07 18:58:22

标签: c# named-pipes iasyncresult waithandle

我正在使用NamedPipeServerStream在两个进程之间进行通信。这是我初始化和连接管道的代码:

void Foo(IHasData objectProvider)
{
    Stream stream = objectProvider.GetData();
    if (stream.Length > 0)
    {
        using (NamedPipeServerStream pipeServer = new NamedPipeServerStream("VisualizerPipe", PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
        {
            string currentDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string uiFileName = Path.Combine(currentDirectory, "VisualizerUIApplication.exe");
            Process.Start(uiFileName);
            if(pipeServer.BeginWaitForConnection(PipeConnected, this).AsyncWaitHandle.WaitOne(5000))
            {
                while (stream.CanRead)
                {
                    pipeServer.WriteByte((byte)stream.ReadByte());
                }
            }
            else
            {
                throw new TimeoutException("Pipe connection to UI process timed out.");
            }
        }
    }
}

private void PipeConnected(IAsyncResult e)
{
}

但它似乎永远不会等待。我经常遇到以下异常:

System.InvalidOperationException:管道尚未连接。    在System.IO.Pipes.PipeStream.CheckWriteOperations()    在System.IO.Pipes.PipeStream.WriteByte(字节值)    在PeachesObjectVisualizer.Visualizer.Show(IDialogVisualizerService windowService,IVisualizerObjectProvider objectProvider)

我认为在等待返回之后,一切都准备好了。

如果我使用pipeServer.WaitForConnection()一切正常,但如果管道没有连接则挂起应用程序不是一个选项。

1 个答案:

答案 0 :(得分:7)

您需要致电EndWaitForConnection

var asyncResult = pipeServer.BeginWaitForConnection(PipeConnected, this);

if (asyncResult.AsyncWaitHandle.WaitOne(5000))
{
    pipeServer.EndWaitForConnection(asyncResult);

    // ...
}

请参阅:IAsyncResult design pattern