如何在 C# 中异步读取/写入命名管道
我有一个承载自定义用户控件的 Windows 窗体。该用户控件启动一个单独的进程(.exe),该进程创建并初始化 NamedPipeServerStream。一旦进程初始化 NamedPipeServerStream,用户控件就会作为 NamedPipeClientStream 连接到它。
这一切都很好。
在 Windows 窗体上,我有一个名为“检查更新”的按钮。按下此按钮时,NamedPipeClientStream 会向服务器发送一条消息,服务器会响应该消息,并显示一个 MessageBox,显示“我被告知要检查更新”。所以我可以告诉这位客户>服务器通信工作正常。
问题就在这里。然后服务器应该向客户端发送一条消息,告诉它现在正在检查更新(因此用户控件可以在服务器收到其命令后更新其状态)。但每当这种情况发生时,一切都会被锁定。
现在我假设这是因为我试图同时读取和写入命名管道?
下面是来自服务器和客户端的一些代码片段。 (这两个代码片段在各自进程中的单独线程中运行,以免阻塞 UI)
GUpdater(命名管道服务器):
private void WaitForClientCommands()
{
// Wait for a connection from a Named Pipe Client (The GUpControl)
pipeStream.WaitForConnection();
pipeConnected = true;
// Create a StreamWriter/StreamReader so we can write/read to the Named Pipe
pipeStreamWriter = new StreamWriter(pipeStream) { AutoFlush = true };
pipeStreamReader = new StreamReader(pipeStream);
// Now that we have a connection, start reading in messages and processing them
while (true)
{
// Skip this time if we are currently writing to the pipe
if(isWritingToPipe) continue;
var message = pipeStreamReader.ReadLine();
if (message == null)
{
// We don't want to hog up all the CPU time, so if no message was reaceived this time, wait for half a second
Thread.Sleep(500);
continue;
}
switch(message)
{
case "CheckForUpdates":
//MessageBox.Show("Told to check for updates");
SendMessageToClient("Checking For Updates, Woot!");
break;
case "DownloadUpdate":
MessageBox.Show("Told to download update");
break;
case "ApplyUpdate":
MessageBox.Show("Told to apply update");
break;
}
}
}
GUpControl(命名管道客户端):
private void WaitForServerCommands()
{
if(!pipeConnected) return;
// Now that we have a connection, start reading in messages and processing them
while (true)
{
// Skip this time if we are currently writing to the pipe
if (isWritingToPipe) continue;
// Attempt to read a line from the pipe
var message = pipeStreamReader.ReadLine();
if (message == null)
{
// We don't want to hog up all the CPU time, so if no message was reaceived this time, wait for half a second
Thread.Sleep(500);
continue;
}
MessageBox.Show("I got a message from the server!!\r\n" + message);
}
}
以下代码片段是负责写入客户端的方法/服务器来自每个组件。 (唯一的区别在于名称,即 SendMessageToClient
和 SendMessageToServer
)
private void SendMessageToServer(string message)
{
if(pipeConnected)
{
isWritingToPipe = true;
pipeStreamWriter.WriteLine(message);
isWritingToPipe = false;
}
}
isWritingToPipe
变量是一个简单的布尔值,当相应进程运行时该布尔值为 true尝试写入命名管道。这是我最初尝试解决这个问题。
非常感谢任何帮助!
I have a Windows form which hosts a custom User Control. This User Control fires up a seperate process (a .exe) which creates and initializes a NamedPipeServerStream. Once the process initializes the NamedPipeServerStream, the User Control connects to it as a NamedPipeClientStream.
This all works fine.
On the Windows form I then have a button called "Check For Updates". When this button is pressed, the NamedPipeClientStream sends a message to the server, to which the server responds which a MessageBox saying "I've been told to check for updates". So I can tell this client > server communication is working fine.
Here's the problem. The server is then supposed to send a message BACK to the client telling it that it's now checking for updates (So the User Control can update its status after verying its command was received by the server). But whenever this happens, everything locks up.
Now I am going to assume that this is because I am attempting to both read AND write to the Named Pipe at the same time?
Below are some code snippets from both the Server and the Client. (Both these snippets run in seperate threads in their respective processes so as to not block the UI)
GUpdater (The Named Pipe Server):
private void WaitForClientCommands()
{
// Wait for a connection from a Named Pipe Client (The GUpControl)
pipeStream.WaitForConnection();
pipeConnected = true;
// Create a StreamWriter/StreamReader so we can write/read to the Named Pipe
pipeStreamWriter = new StreamWriter(pipeStream) { AutoFlush = true };
pipeStreamReader = new StreamReader(pipeStream);
// Now that we have a connection, start reading in messages and processing them
while (true)
{
// Skip this time if we are currently writing to the pipe
if(isWritingToPipe) continue;
var message = pipeStreamReader.ReadLine();
if (message == null)
{
// We don't want to hog up all the CPU time, so if no message was reaceived this time, wait for half a second
Thread.Sleep(500);
continue;
}
switch(message)
{
case "CheckForUpdates":
//MessageBox.Show("Told to check for updates");
SendMessageToClient("Checking For Updates, Woot!");
break;
case "DownloadUpdate":
MessageBox.Show("Told to download update");
break;
case "ApplyUpdate":
MessageBox.Show("Told to apply update");
break;
}
}
}
GUpControl (The Named Pipe Client):
private void WaitForServerCommands()
{
if(!pipeConnected) return;
// Now that we have a connection, start reading in messages and processing them
while (true)
{
// Skip this time if we are currently writing to the pipe
if (isWritingToPipe) continue;
// Attempt to read a line from the pipe
var message = pipeStreamReader.ReadLine();
if (message == null)
{
// We don't want to hog up all the CPU time, so if no message was reaceived this time, wait for half a second
Thread.Sleep(500);
continue;
}
MessageBox.Show("I got a message from the server!!\r\n" + message);
}
}
The following snippet is the method that is responsible for writing to the Client/Server from each component. (The only difference is in the name, i.e. SendMessageToClient
and SendMessageToServer
)
private void SendMessageToServer(string message)
{
if(pipeConnected)
{
isWritingToPipe = true;
pipeStreamWriter.WriteLine(message);
isWritingToPipe = false;
}
}
The isWritingToPipe
variable is a simple bool that is true when the respective process is attempting to write to the Named Pipe. This was my initial attempt at solving the problem.
Any help is much appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
System.IO.Pipes.PipeStream 有一个方法 WaitForPipeDrain() ,这是在交换消息时管理客户端和服务器之间协调的正确方法。
管道的 TransmissionMode 也可能会产生影响:您使用的是字节模式还是消息模式?例如,我不确定将流包装在 StreamReader 中与管道消息模式语义的配合效果如何。有关消息模式的更多信息,请参阅这个答案。
System.IO.Pipes.PipeStream
has a methodWaitForPipeDrain()
which is the correct way to manage coordination between the client and server when exchanging messages.The TransmissionMode for the pipe may also be affecting things: are you using Byte mode or Message mode? I'm not sure how well wrapping the stream in a StreamReader plays with the pipe message mode semantics, for example. See this SO answer for more on message mode.
当您向服务器发送信号以检查更新时,请在 BackgroundWorker 类中执行此操作
when you send a signal to server for checking updates then do it in BackgroundWorker class
事实证明,这个问题的解决方案是重新思考软件的设计。
UserControl 不是在更新过程的每个步骤中都与单独的应用程序进行对话,而是自行处理所有内容,最后在需要应用更新时(这涉及覆盖应用程序文件,因此需要在更新过程中使用单独的过程)第一名)它只是使用 Process.Start("...") 以及一些命令行参数来调用单独的进程来完成工作。
这是一个比尝试为此任务进行进程间通信简单得多的解决方案。
不过,如果能找出我的双向通信不起作用的原因,那就太好了。
The solution to this problem turned out to be a matter of rethinking the design of the software.
Instead of having a UserControl that talks to a seperate application each step of the Update process, the UserControl handles it all itself and then finally when it needs to apply the update (which involves overwriting application files, hence the need for a seperate process in the first place) it simply uses Process.Start("...") along with some command line arguements to call a seperate process to finish the job.
A much simpler solution than trying to do Inter-Process Communication for this task.
Still, it would have been nice to find out why my Bi-Directional communication wasn't working.