如何保持控制台c#应用程序运行并从标准输入流读取输入(不是连续的)

本文关键字:输入 连续 读取 标准输入流 控制台 何保持 应用程序 运行 | 更新日期: 2023-09-27 18:29:11

我有一个控制台c#应用程序(本地消息应用程序),它通过命名管道连接到WinForms。控制台应用程序是一个与chrome连接的本地消息应用程序。WinForm将命令发送到控制台应用程序,以开始读取标准输入流,从而将消息发送到chrome并发送到WinForm。我不知道如何让控制台应用程序保持活动状态,这样它就可以等待附加的事件从winform获取命令并读取标准输入流。?

这是我的主要职能。

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

这是用于从命名的Pipe 获取消息的事件处理程序

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);
}

如何保持控制台c#应用程序运行并从标准输入流读取输入(不是连续的)

您应该尝试使用AutoResetEvent-请参阅http://msdn.microsoft.com/en-us/library/system.threading.autoresetevent(v=vs.110).aspx。
通过这种方式,主线程在侦听器线程上等待,直到事件设置完毕,然后才终止
如果使用.NET 4.5,则应使用asyncawait关键字加上Task.Run()->请参阅http://msdn.microsoft.com/en-us/library/hh191443.aspx