为什么我的 NamedPipeServerStream 不等待?
我正在使用 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)
我认为等待返回后一切都应该准备就绪。
如果我使用 pipelineServer.WaitForConnection() 一切正常,但如果管道未连接则挂起应用程序不是一个选项。
I'm working with a NamedPipeServerStream to communicate between two processes. Here is the code where I initialize and connect the pipe:
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)
{
}
But it never seems to wait. I constantly get the following exception:
System.InvalidOperationException: Pipe hasn't been connected yet.
at System.IO.Pipes.PipeStream.CheckWriteOperations()
at System.IO.Pipes.PipeStream.WriteByte(Byte value)
at PeachesObjectVisualizer.Visualizer.Show(IDialogVisualizerService windowService, IVisualizerObjectProvider objectProvider)
I would think that after the wait returns everything should be ready to go.
If I use pipeServer.WaitForConnection() everything works fine, but hanging the application if the pipe doesn't connect is not an option.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要调用 结束等待连接。
请参阅:IAsyncResult 设计模式。
You need to call EndWaitForConnection.
See: IAsyncResult design pattern.