【问题标题】:How to keep a console c# application running and reading input from standard input stream (not continously)如何保持控制台 C# 应用程序运行并从标准输入流读取输入(不连续)
【发布时间】:2014-11-04 07:27:48
【问题描述】:

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

这是我的主要功能。

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

【问题讨论】:

  • @Alex: Console.ReadLine 在读取 Console.OpenStandardInput() 的情况下将不起作用;在 OpenStandardStreamIn() 中; .也许我也应该粘贴代码。查看我的编辑。
  • 是的,刚刚看到您的评论。我不知道:)
  • @Alex:没有问题。 :)
  • 那么,这个控制台应用程序什么时候应该退出?对事件的任何等待操作都可以使其保持活动状态。如果要从另一个进程中停止此类程序,请使用命名事件。如果管道发生错误,您也可以设置此事件。
  • @AlexFarber : 谢谢,我会试试 Alex 并告诉你

标签: c# .net winforms console-application


【解决方案1】:

您应该尝试使用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

【讨论】:

    猜你喜欢
    • 2013-09-27
    • 1970-01-01
    • 2021-08-03
    • 2012-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-18
    相关资源
    最近更新 更多