【发布时间】:2012-02-07 11:26:32
【问题描述】:
有时,在某些机器上,使用我的程序的客户端经常出现“管道正在关闭”异常,但很少见。这发生在 .WaitForConnection() 上的 NamedPipeServerStream 上。之后,应用程序完全崩溃并释放 Windows 异常。当 NamedPipeClientStream 将信息传输到独立应用程序时会发生这种情况。
主要功能: 我编写了几个与 NamedPipes 通信的工具(Office 工具栏、一个服务、一个独立的 .net 应用程序和一个小启动 exe)。 服务运行一个始终打开的 NamedPipeServerStream(处于状态 .WaitForConnection();),独立应用程序也有一个 NamedPipeServerStream。 工具栏和启动程序 .exe 与服务通信。然后服务与独立应用程序。
什么样的问题可以释放管道被关闭的异常? 服务器是否有可能将信息发送到独立应用程序但由于独立应用程序未准备好或其他原因而提前关闭流?在每个 NamedPipeClientStream 上,如果 pipeClient.IsConnected 在我关闭 pipeclient 之前,我会执行 waitforpipedrain ..
感谢帮助
编辑:这里是客户端流的示例
using (NamedPipeClientStream pipeClient =
new NamedPipeClientStream(".", pipename, PipeDirection.Out))
{
// Wait for a client to connect
try
{
pipeClient.Connect(3000);
// send params to the form
using (StreamWriter sw = new StreamWriter(pipeClient))
{
sw.AutoFlush = true;
sw.WriteLine(sendtext);
}
}
// Catch the IOException that is raised if the pipe is
// broken or disconnected.
catch (Exception e)
{
if (sid != "")
{
connections.Remove(conName);
}
eventLog1.WriteEntry("SendText Fehler 1 " + e.Message);
}
finally
{
if (pipeClient.IsConnected)
{
pipeClient.WaitForPipeDrain();
}
pipeClient.Close();
pipeClient.Dispose();
}
管道服务器示例(在单独的线程中运行)
NamedPipeServerStream pipeServer;
PipeSecurity pipe_security = CreateSystemIoPipeSecurity();
do
string pipename = global::TOfficeCenter.Properties.Settings.Default.pipename;
string aText = "";
pipeServer = new NamedPipeServerStream(pipename, PipeDirection.In, ONE_INSTANCE, PipeTransmissionMode.Byte,
PipeOptions.None, IN_BUF_SIZE, OUT_BUF_SIZE, pipe_security);
try
{
// Verbindung zu TOfficeCenter.exe aufbauen
try
{
IsWaiting = true;
pipeServer.WaitForConnection();
IsWaiting = false;
using (StreamReader sr = new StreamReader(pipeServer))
{
string temp;
while ((temp = sr.ReadLine()) != null)
{
aText = aText + temp;
}
}
try
{
if (aText == "")
{
empfang(null);
}
else
{
if (aText != "KillPipe")
{ // XML empfangen
XmlDocumentTC xml = new XmlDocumentTC();
xml.LoadXml(aText);
empfang(xml);
}
}
}
catch (Exception)
{
empfang(null);
}
}
catch
{...........
}
}
catch (Exception e)
{...........
}
} while (running);
pipeServer.Close();
【问题讨论】:
-
您确定您没有在其中一个应用程序中意外关闭管道吗?
-
我猜测客户端数据会导致服务器异常。这是未处理的,因此服务器关闭,在客户端产生该异常。改进服务器中的异常日志记录以更好地诊断此问题,实现 AppDomain.UnhandledException 事件。
-
感谢您的回答。
-
不想发送,对不起...在客户端,每次我在管道中写一些东西时,我都会关闭客户端流。在管道服务器端,管道服务器得到一些数据后,它再次重新启动管道。 @HansPassant:当服务器位于 PipeServer.WaitForConnection 时发生异常。我不知道为什么抛出异常的同一个应用程序会完全崩溃。我将发布一些管道客户端和管道服务器端的示例
-
嘿...
throw new PipeIsBeingClosedException();。好标题。 ;)