c# – 我的NamedPipeServerStream为什么不等?
发布时间:2020-12-16 01:35:23 所属栏目:百科 来源:网络整理
导读:我正在使用NamedPipeServerStream在两个进程之间进行通信.这是我初始化和连接管道的代码: void Foo(IHasData objectProvider){ Stream stream = objectProvider.GetData(); if (stream.Length 0) { using (NamedPipeServerStream pipeServer = new NamedPip
我正在使用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:管道尚未连接. 我认为在等待返回之后,一切都应该准备好了. 如果我使用pipeServer.WaitForConnection()一切正常,但如果管道没有连接则挂起应用程序不是一个选项. 解决方法
你需要拨打
EndWaitForConnection.
var asyncResult = pipeServer.BeginWaitForConnection(PipeConnected,this); if (asyncResult.AsyncWaitHandle.WaitOne(5000)) { pipeServer.EndWaitForConnection(asyncResult); // ... } 见:IAsyncResult design pattern. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |