我有一个IPC问题。我已经在windows服务中创建了一个NamedPipeServer:
serverPipe = new NamedPipeServerStream(Constants.PIPE_NAME, PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);
Thread thread = new Thread(new ThreadStart(pipeWork));
thread.Start();
pipeWork在哪里
private static void pipeWork()
{
try
{
byte[] buffer = new byte[1024];
while (true)
{
if (!serverPipe.IsConnected)
serverPipe.WaitForConnection();
int nr = serverPipe.Read(buffer, 0, buffer.Length);
String str=Encoding.Default.GetString(buffer);
…
}
}
catch (Exception ex)
{
}
}
在Windows窗体中,我有一个客户端
clientPipe = new NamedPipeClientStream(".", PhotoServiceClassLibrary.Constants.PIPE_NAME, PipeDirection.InOut,PipeOptions.Asynchronous);
clientPipe.Connect();
clientPipe.ReadMode = PipeTransmissionMode.Message;
pipeThread=new Thread(new ThreadStart(pipeWork));
pipeThread.Start();
pipeWork在哪里
private void pipeWork()
{
try
{
while (true)
{
using (StreamReader sr = new StreamReader(clientPipe))
{
string message;
while ((message = sr.ReadLine()) != null)
{
…
}
}
}
}
catch (Exception ex)
{
}
}
我希望当服务开始从windows窗体中禁用ContextMenuStrip的操作时,该服务将向StreamWriter sw写入一条消息:
StreamWriter write = null;
write = new StreamWriter(serverPipe);
if (serverPipe.IsConnected)
{
write.Write(message);
write.Flush();
}
代码是正确的,因为我创建了另一个windows窗体来测试它,它实现了windows服务和windows窗体管道服务器之间的通信,-> windows窗体管道客户端运行良好。问题是windows窗体-客户端管道无法接收来自windows服务-服务器管道的消息。
我知道WCF可能是一个更好的想法,但我想知道为什么在低级IPC上不能工作。为什么?我看到了一种非常奇怪的行为。我的服务与windows表单进行了2次交互:1.我的服务是为下载一些照片而设计的。当他开始下载时,他向windows表单发送一条消息,通知他这一点。2.当我停止服务时,他会向windows forms发送一条消息,他也会停止。我刚刚发现,这两条消息只有在服务停止后才会到达windows agent。有人能解释一下原因吗?
发布于 2009-06-06 13:38:23
我希望这不是你真正的代码。在ThreadStart处理程序的代码周围有try/catch块是很好的(否则异常将悄悄地删除线程)。但是,如果您没有在catch块中记录异常,那么它实际上也同样糟糕。
您有一个谜团(服务器没有接收到消息),而您隐藏了信息(发生了异常)。如果你没有隐藏信息,你可能已经解开了谜团(服务器没有收到消息,因为发生了异常)。
发布于 2013-08-19 06:31:20
我正在尝试实现同样的事情。
我注意到您在NamedPipeServerStream (serverPipe)构造函数中传递了PipeTransmissionMode.Message枚举。这意味着流将包含字符串。
但在pipeWork中,您是以字节数组的形式读取它们。
在MSDN上查看本文中的示例:http://msdn.microsoft.com/en-us/library/system.io.pipes.namedpipeclientstream.aspx
https://stackoverflow.com/questions/960064
复制