【问题标题】:Why doesn't my NamedPipeServerStream wait?为什么我的 NamedPipeServerStream 不等待?
【发布时间】:2010-04-07 18:58:21
【问题描述】:

我正在使用 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() 一切正常,但如果管道未连接,则挂起应用程序不是一种选择。

【问题讨论】:

    标签: c# named-pipes iasyncresult waithandle


    【解决方案1】:

    您需要致电EndWaitForConnection

    var asyncResult = pipeServer.BeginWaitForConnection(PipeConnected, this);
    
    if (asyncResult.AsyncWaitHandle.WaitOne(5000))
    {
        pipeServer.EndWaitForConnection(asyncResult);
    
        // ...
    }
    

    请参阅:IAsyncResult design pattern

    【讨论】:

    • 我尝试了这种方法,现在它在连接前等待大约 10 秒,但是当我不使用 BeginWait 时,它会立即连接。根据 MSDN AsyncWaitHandle.WaitOne(5000) 阻塞直到发出信号,但显然情况并非如此。
    • 抱歉,我的复制代码有误,导致它挂了一会儿。我修复了代码,现在可以了。谢谢!
    • 您介意分享您为修复它所做的工作吗?我也有同样的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-23
    • 2019-11-12
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    相关资源
    最近更新 更多