2013-07-10 107 views
10

我有一個windows服務正在通過命名管道與gui應用程序進行通信。因此,我有一個線程正在運行,正在等待應用程序連接,如果我一次執行,它正在運行良好。但是,如果線程正在創建命名管道流服務器的新實例,則已建立的連接將中斷,並且我將獲取所有實例繁忙的異常。其中拋出異常代碼片段是這樣的:在創建新的管道服務器流NamedPipeServerStream ps = new NamedPipeServerStream("mytestp")所述第二時間時所有實例在創建命名管道時出現異常

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",PipeDirection.Out,10);

它的默認值似乎是-1它的工作原理。這會導致另一個問題,但不是那麼重要的問題:有人知道它爲什麼是-1而不是1時,它的行爲如同beeing 1?

+0

說[這裏](https://msdn.microsoft.com/en-us/library/bb355760(V = vs.110)的.aspx#ANCHOR_2)的默認值是1。然而,解決方案也解決了我的問題,歡呼!我會考慮提交它作爲答案,會得到我的投票。 –

+0

我剛纔看了一下關於「-1」的.Net代碼,它說:win32允許固定值1-254或255來表示系統允許的最大值。我們通過MaxAllowedServerInstances常量將255暴露爲-1(無限制)。這是一致的,例如以-1表示無限超時等 – derape

回答

0

還有的NamedPipeServerStream構造函數的兩個重載是指定一個默認的maxNumberOfServerInstances變量,即:

public NamedPipeServerStream(String pipeName) 

public NamedPipeServerStream(String pipeName, PipeDirection direction) 

望着reference source證明了此默認爲而不是-1。 這解釋了您觀察到的行爲。

可能的解決方案是:

  1. 使用一個構造函數允許你指定的極限,並通過大於1

  2. 相同1的值,並且使用內置的恆NamedPipeServerStream.MaxAllowedServerInstances要求操作系統能夠分配的最大數量的句柄。