【发布时间】:2010-10-11 02:35:55
【问题描述】:
我启动了我的应用程序,它产生了许多线程,每个线程都创建一个 NamedPipeServer(.net 3.5 为命名管道 IPC 添加了托管类型)并等待客户端连接(块)。代码按预期运行。
private void StartNamedPipeServer()
{
using (NamedPipeServerStream pipeStream =
new NamedPipeServerStream(m_sPipeName, PipeDirection.InOut, m_iMaxInstancesToCreate, PipeTransmissionMode.Message, PipeOptions.None))
{
m_pipeServers.Add(pipeStream);
while (!m_bShutdownRequested)
{
pipeStream.WaitForConnection();
Console.WriteLine("Client connection received by {0}", Thread.CurrentThread.Name);
....
现在我还需要一个 Shutdown 方法来彻底关闭这个过程。我尝试了通常的布尔标志 isShutdownRequested 技巧。但是管道流在 WaitForConnection() 调用上保持阻塞,并且线程不会死亡。
public void Stop()
{
m_bShutdownRequested = true;
for (int i = 0; i < m_iMaxInstancesToCreate; i++)
{
Thread t = m_serverThreads[i];
NamedPipeServerStream pipeStream = m_pipeServers[i];
if (pipeStream != null)
{
if (pipeStream.IsConnected)
pipeStream.Disconnect();
pipeStream.Close();
pipeStream.Dispose();
}
Console.Write("Shutting down {0} ...", t.Name);
t.Join();
Console.WriteLine(" done!");
}
}
加入永远不会返回。
我没有尝试但可能可行的一个选项是调用 Thread.Abort 并吃掉异常。但这感觉不对..任何建议
2009 年 12 月 22 日更新
很抱歉没有早点发布。这是我收到的 Kim Hamilton(BCL 团队)的回复
做可中断的“正确”方式 WaitForConnection 是调用 BeginWaitForConnection,处理新的 回调中的连接,然后关闭 停止等待的管道流 连接。如果管道关闭, EndWaitForConnection 将抛出 ObjectDisposedException 其中 回调线程可以捕获、清理 任何松散的末端,然后干净地退出。
我们意识到这一定是常见的 问题,所以我团队中的某个人是 计划尽快写博客。
【问题讨论】:
标签: c# .net-3.5 named-pipes