gpt4 book ai didi

c# - 命名管道创建时所有实例都忙异常

转载 作者:可可西里 更新时间:2023-11-01 09:16:12 26 4
gpt4 key购买 nike

我有一个 Windows 服务,它通过命名管道与一个图形用户界面应用程序通信。因此,我有一个正在运行的线程正在等待应用程序连接,如果我这样做一次,它运行良好。但是,如果线程正在创建命名管道流服务器的新实例,则已经建立的连接将中断,并且我会收到所有实例繁忙的异常。抛出异常的代码片段是这样的:

class PipeStreamWriter : TextWriter
{

static NamedPipeServerStream _output = null;
static StreamWriter _writer = null;
static Thread myThread = null;

public PipeStreamWriter()
{
if (myThread == null)
{
ThreadStart newThread = new ThreadStart(delegate{WaitForPipeClient();});
myThread = new Thread(newThread);
myThread.Start();
}
}

public static void WaitForPipeClient()
{
Thread.Sleep(25000);
while (true)
{
NamedPipeServerStream ps = new NamedPipeServerStream("mytestp");
ps.WaitForConnection();
_output = ps;
_writer = new StreamWriter(_output);

}
}

第二次创建新的管道服务器流NamedPipeServerStream ps = new NamedPipeServerStream("mytestp")时抛出异常。

编辑:

我找到了答案,它在指定最大服务器实例数时有效NamedPipeServerStream ps = new NamedPipeServerStream("mytestp",PipeDirection.Out,10);

这个的默认值似乎是-1。这引出了另一个但不是那么重要的问题:有人知道为什么当它表现得像蜜蜂 1 时它是 -1 而不是 1?

最佳答案

NamedPipeServerStream 构造函数有两个重载,它们将默认值分配给 maxNumberOfServerInstances 变量,即:

public NamedPipeServerStream(String pipeName)

public NamedPipeServerStream(String pipeName, PipeDirection direction)

查看 reference source证明此默认值是 1 而不是 -1。这解释了您观察到的行为。

可能的解决方案是:

  1. 使用允许您指定限制的构造函数,并传递大于 1 的值

  2. 与 1 相同,并使用内置常量 NamedPipeServerStream.MaxAllowedServerInstances 来询问操作系统能够分配的最大句柄数。

    <

关于c# - 命名管道创建时所有实例都忙异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17570652/

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