gpt4 book ai didi

c# - 关闭在 NamedPipeServer#WaitForConnection 上阻塞的线程的好方法是什么?

转载 作者:IT王子 更新时间:2023-10-29 04:01:15 26 4
gpt4 key购买 nike

我启动我的应用程序,该应用程序产生许多线程,每个线程创建一个 NamedPipeServer(.net 3.5 添加了命名管道 IPC 的托管类型)并等待客户端连接( block )。代码按预期运行。

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 方法来彻底关闭这个进程。我尝试了通常的 bool 标志 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 团队)那里收到的回复

The "right" way to do an interruptible WaitForConnection is to call BeginWaitForConnection, handle the new connection in the callback, and close the pipe stream to stop waiting for connections. If the pipe is closed, EndWaitForConnection will throw ObjectDisposedException which the callback thread can catch, clean up any loose ends, and exit cleanly.

We realize this must be a common question, so someone on my team is planning to blog about this soon.

最佳答案

这很俗气,但这是我开始工作的唯一方法。创建一个“假”客户端并连接到您的命名管道以通过 WaitForConnection。每次都有效。

此外,即使是 Thread.Abort() 也没有为我解决这个问题。


_pipeserver.Dispose();
_pipeserver = null;

using (NamedPipeClientStream npcs = new NamedPipeClientStream("pipename"))
{
npcs.Connect(100);
}

关于c# - 关闭在 NamedPipeServer#WaitForConnection 上阻塞的线程的好方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/607872/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com