【问题标题】:C# Console Application - How do I always read input from the console?C# 控制台应用程序 - 我如何始终从控制台读取输入?
【发布时间】:2014-05-18 22:17:09
【问题描述】:

我目前正在编写一个使用大量多线程的控制台应用程序。我希望能够始终允许用户在控制台中输入内容但是,线程会定期向控制台输出,但我希望用户始终能够将内容输入控制台并让我处理输入.

我将如何实现这一目标?我在网上没有找到任何相关信息?

提前致谢!

这是c#顺便说一句!

【问题讨论】:

    标签: c# multithreading input console-application


    【解决方案1】:

    编辑。我几年前的原始答案依赖于用户输入一个魔术字符串来结束控制台侦听器,而忽略了 CTL+C 已经是默认的取消信号。

    class Program
    {
        readonly static CancellationTokenSource _cancelTokenSrc = new CancellationTokenSource();
    
        static void Main(string[] args)
        {
            // CTL + C is the built-in cancellation for console apps; 
            Console.CancelKeyPress += Console_CancelKeyPress;
            CancellationToken cancelToken = _cancelTokenSrc.Token;
    
            Console.WriteLine("Type commands followed by 'ENTER'");
            Console.WriteLine("Press CTL+C to Terminate");
            Console.WriteLine();
            try
            {
                // thread that performs background work until cancelled
                Task.Run(() => DoWork(), cancelToken);
                // thread that listens for keyboard input until cancelled
                Task.Run(() => ListenForInput(), cancelToken);
                // continue listening until cancel signal is sent
                cancelToken.WaitHandle.WaitOne();
                cancelToken.ThrowIfCancellationRequested();
            }
            catch (OperationCanceledException)
            {
                Console.WriteLine("Operation Canceled.");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
        }
    
        static void ListenForInput()
        {
            while (true)
            {
                string userInput = Console.ReadLine();
                if(!String.IsNullOrWhiteSpace(userInput))
                    Console.WriteLine($"Executing user command {userInput}...");
            }
        }
    
        static void DoWork()
        {
            while (true)
            {
                Thread.Sleep(3000);
                Console.WriteLine("Doing work...");
            }
        }
    
        static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
        {
            // we want to cancel the default behavior so we can send the cancellation signal
            // to our background threads and not just terminate here
            e.Cancel = true;
            Console.WriteLine("Cancelling...");
            _cancelTokenSrc.Cancel();
        }
    }
    

    【讨论】:

    • 不,这不起作用......当我在控制台中输入任何内容时它就会退出?
    • @user3228693 对于第一篇基于仅通过用户输入取消线程的模型的帖子表示歉意。要输入多个命令,侦听器线程需要循环运行。我还添加了一个虚拟工作线程,以便示例运行并演示该概念。
    猜你喜欢
    • 1970-01-01
    • 2023-03-21
    • 2023-04-03
    • 2015-08-17
    • 2014-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    相关资源
    最近更新 更多