Message pump in a console application

后端 未结 2 684
醉梦人生
醉梦人生 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<ConsoleKeyInfo>();
    
    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.

    0 讨论(0)
  • 2021-01-12 02:54

    You could use the event handling mechanism of .NET. Reposting from here.

    Imports System.Threading.Thread
    
    Module Module1
        Private Second As Integer = 1
        Private Tick As New Timers.Timer(1000)
    
        Sub Main()
    
            AddHandler tick.Elapsed, AddressOf Ticker 'Event for the timer tick
    
            Dim NewThread As System.Threading.Thread = New System.Threading.Thread(AddressOf LookForKeyPress) 'New thread to check for key press
            NewThread.Start() 'Start thread
    
            Console.WriteLine("Now awaiting key presses...")
            tick.Enabled = True 'Enable the timer
        End Sub
    
        Private Sub Ticker()
            'every tick this sub is called and the seconds are displayed till a key is pressed
            Console.WriteLine(Second)
            Second += 1
    
        End Sub
    
        Private Sub LookForKeyPress()
    
            While True
                Dim k As ConsoleKeyInfo = Console.ReadKey() 'read for a key press
                If Not k.Key.ToString.Length <= 0 Then 'check the length of the key string pressed, mainly because the key in this case will be apart of the system.consolekey
                    Console.WriteLine(Environment.NewLine & "Key Pressed: " & k.Key.ToString) 'display the key pressed
                    Second = 1 'restart the timer
                End If
            End While
    
        End Sub
    
    End Module
    

    Hope I helped!

    0 讨论(0)
提交回复
热议问题