当时间流逝时,我如何收集按键信息?



我想写一个循环,收集按键(从键盘),并做一个动作每秒左右。会有一些从键盘读取的方法:

whenever (Console.KeyPressed != null) {
    input_buffer.Add(Console.KeyPressed);
}

会有一些循环发生:

while (!done) {
    if (input_buffer.NotEmpty()) { do_stuff(input_buffer.Pop()); }
    do_other_stuff();
    wait(0.5 seconds);
}

如果用户按下一个键,它会在下一次更新时被处理。如果他们没有按下一个键,下一次更新还是会发生。

如果你使用的是。net 4,你可以使用下面的代码。它使用ConcurrentQueue存储按键,ManualResetEventSlim用于信令,Task来自任务并行库用于异步运行两个代码部分。

using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
namespace Test
{
    public class Program
    {
        private static ConcurrentQueue<ConsoleKeyInfo> _keypresses = new ConcurrentQueue<ConsoleKeyInfo>();
        private static ManualResetEventSlim _stopEvent = new ManualResetEventSlim();
        public static void Main()
        {
            Console.TreatControlCAsInput = true;
            var keyReaderTask = Task.Factory.StartNew(ReadKeys);
            var keyProcessingTask = Task.Factory.StartNew(ProcessKeys);
            _stopEvent.Wait();
            keyReaderTask.Wait();
            keyProcessingTask.Wait();
        }
        public static void ReadKeys()
        {
            while (true)
            {
                var keyInfo = Console.ReadKey(true);
                if (keyInfo.Modifiers == ConsoleModifiers.Control && keyInfo.Key == ConsoleKey.C)
                {
                    break;
                }
                _keypresses.Enqueue(keyInfo);
            }
            _stopEvent.Set();
        }
        public static void ProcessKeys()
        {
            while (!_stopEvent.IsSet)
            {
                if (!_keypresses.IsEmpty)
                {
                    Console.Write("Keys: ");
                    ConsoleKeyInfo keyInfo;
                    while (_keypresses.TryDequeue(out keyInfo))
                    {
                        Console.Write(keyInfo.KeyChar);
                    }
                    Console.WriteLine();
                }
                _stopEvent.Wait(1000);
            }
        }
    }
}

最新更新