【问题标题】:All instances busy exception on named pipe creation创建命名管道时所有实例都忙异常
【发布时间】:2013-07-10 12:26:57
【问题描述】:

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

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?

【问题讨论】:

  • here 默认值为1。尽管如此,您的解决方案也解决了我的问题,干杯!我会考虑提交它作为答案,会得到我的投票。
  • 我刚刚查看了有关“-1”的 .Net 代码,它说:win32 允许 1-254 或 255 的固定值表示系统允许的最大值。我们通过 MaxAllowedServerInstances 常量将 255 公开为 -1(无限制)。这是一致的,例如-1 作为无限超时,等等
  • 请注意,reference source 还表示 MaxAllowedServerInstances (-1) 是指定无限制的唯一方式。虽然 -1 在内部转换为 255,但传递 255 被认为是无效的并且会抛出异常。 (可能如何解释“将 255 暴露为 -1”,即“仅作为”而不是“也作为”。)

标签: c# named-pipes


【解决方案1】:

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

public NamedPipeServerStream(String pipeName)

public NamedPipeServerStream(String pipeName, PipeDirection direction)

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

可能的解决方案是:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-02
    • 1970-01-01
    • 1970-01-01
    • 2011-07-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    相关资源
    最近更新 更多