Message pump in a console application

后端 未结 2 686
醉梦人生
醉梦人生 2021-01-12 02:22

I have a fairly simple console application written in .NET. Sometimes the application is run in batch mode without an operator, other times it is run \"out of pocket\". If i

2条回答
  •  攒了一身酷
    2021-01-12 02:30

    You could start a thread that reads key presses in the background. Add the keys to a blocking queue and wait in the main thread for the queue to be filled, e.g.

    var queue = new BlockingCollection();
    
    new Thread(() =>
    {
        while (true) queue.Add(Console.ReadKey(true));
    })
    { IsBackground = true }.Start();
    
    
    Console.Write("Welcome! Please press a key: ");
    
    ConsoleKeyInfo cki;
    
    if (queue.TryTake(out cki, TimeSpan.FromSeconds(10))) //wait for up to 10 seconds
    {
        Console.WriteLine();
        Console.WriteLine("You pressed '{0}'", cki.Key);
    }
    else
    {
        Console.WriteLine();
        Console.WriteLine("You did not press a key");
    }
    

    Both the background thread and the main thread will sleep (utilize 0% processor time) while they're waiting for ReadKey and TryTake to return respectively.

提交回复
热议问题