2014-11-04 33 views
0

我有一個控制檯c#應用程序(本機通訊應用程序),它通過命名管道連接到winform。控制檯應用程序是與Chrome連接的本地消息應用程序。 Winform將命令發送給控制檯應用程序,開始讀取標準輸入流,以便將消息發送到chrome並將其發送到winfrom。 我不知道如何讓控制檯應用程序保持活動狀態,以便它可以等待附件從winform獲取命令並讀取標準輸入流。如何保持控制檯c#應用程序運行並從標準輸入流讀取輸入(不是連續的)

這是我的主要功能。

static void Main(string[] args) 
    { 
      StartChannel();    
    } 

這是從命名管道

獲取消息
public void StartChannel() 
     { 
      _pipeServer = new PipeServer(); 
      _pipeServer.PipeMessage += new DelegateMessage(PipesMessageHandler); 
      _pipeServer.Listen(AppConstant.IPC_ConsoleReaderPipe); 
     } 

     private void PipesMessageHandler(string message) 
     { 
      if(message ="Start") 
       StartListener(); 
     } 

**這是我的問題中心的事件處理程序。在執行完StartListener後,控制檯應用程序關閉。我如何讓它在單獨的線程中運行。因此,它不應該阻止該NamedPipe通信**

private static void StartListener() 
{ 
     wtoken = new CancellationTokenSource(); 
     readInputStream = Task.Factory.StartNew(() => 
     { 
      wtoken.Token.ThrowIfCancellationRequested(); 
      while (true) 
      { 
       if (wtoken.Token.IsCancellationRequested) 
       { 
        wtoken.Token.ThrowIfCancellationRequested(); 
       } 
       else 
       { 
        OpenStandardStreamIn(); 
       } 
      } 
     }, wtoken.Token 
     ); 
    } 
} 

public static void OpenStandardStreamIn() 
     { 
       Stream stdin = Console.OpenStandardInput(); 
       int length = 0; 
       byte[] bytes = new byte[4]; 
       stdin.Read(bytes, 0, 4); 
       length = System.BitConverter.ToInt32(bytes, 0); 
       string input = ""; 
       for (int i = 0; i < length; i++) 
       { 
        input += (char)stdin.ReadByte(); 
       } 
       Console.Write(input); 
      } 
+0

@Alex:到Console.ReadLine不會在工作的情況下讀取Console.OpenStandardInput();在OpenStandardStreamIn(); 。可能是我應該粘貼代碼也。看我的編輯。 – 2014-11-04 07:34:48

+0

是的,只是看到你的評論。我不知道:) – Alex 2014-11-04 07:38:17

+0

@Alex:沒有問題。 :) – 2014-11-04 07:40:43

回答

相關問題