我启动了我的应用程序,它产生了许多线程,每个线程都创建一个 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 回调线程可以捕获,清理任何松散的末端,并干净地退出。
我们意识到这一定是一个常见问题,所以我团队中的某个人计划很快在博客上讨论这个问题。