c# 不完整的 Console.ReadKey() 调用我不希望用户完成

我正在学习套接字消息传递。我在 while 循环中中断了 Console.ReadKey() 并且很多调用最终都未完成。我正在尝试找到一种方法来删除不完整的调用,而无需用户将其全部输入。

我见过

while(Console.KeyAvailable){Console.ReadKey(true);}

但我有相反的问题,太多的电话没有足够的击键。

如何向 Console.ReadLine() 添加超时? 这个问题让我到了现在的位置,但它并没有解决我当前的问题。

using System;

using System.Threading;


class Program

{

    static void Main(string[] args)

    {

        DontLockOnCharGet bug = new DontLockOnCharGet();

        bug.Setup();

    }

}


public class DontLockOnCharGet

{

    public void Setup()

    {

        while (true) { DontLockCharGet(); }

    }


    public void DontLockCharGet()

    {

        while (true)

        {

            // used to interrupt the Console.ReadKey() function

            AutoResetEvent getInput = new AutoResetEvent(false);

            AutoResetEvent gotInput = new AutoResetEvent(false);


            // Console.ReadKey() assigns to input

            char input = ' ';


            //Lambda used to get rid of extra class

            Thread tom = new Thread(() =>

            {

                getInput.WaitOne(); // Waits for getInput.Set()


                //The problem with this is the read keys stacking up

                // causing the need for a lot of keystrokes

                input = Console.ReadKey().KeyChar;


                gotInput.Set();

            })

            {

                IsBackground = true

            };

            // Starts Lambda function

            tom.Start(); 


            // Allows thread to pass WaitOne() in Lambda

            getInput.Set(); 

            // Gives some milliseconds for before stopping Lambda exe

            gotInput.WaitOne(2000);


            if (input == 'S' || input == 's')

            {

                break;

            }

            // thinking I would put the solution here

            //...

        }

        //Do stuff if input is s || S

        Console.Write("end: ");

    }

}

我希望能够按 's' || 'S' 然后输入一条消息,但根据我等待的时间长短,我可能需要按住 's' 很长时间。



倚天杖
浏览 76回答 1
1回答

翻阅古今

问题出在new Thread(()=> { ... });This is creating a new function 而不仅仅是新函数调用。正在创建的函数应该像这样移动到一个单独的函数中private void ReadKey(){        // Waits for getInput.Set()        getInput.WaitOne();        //The problem with this is the read keys stacking up        // causing the need for a lot of keystrokes        input = Console.ReadKey().KeyChar;        gotInput.Set();}在班级里面。做这些AutoResetEvent getInput, gotInput;char input;类变量并在内部初始化它们Setup(){...}最后Thread tom = new Thread(ReadKey);在当前正在制作新功能的地方调用。注意:此答案不适用于最佳实践,但会得到一个原型来工作。
打开App,查看更多内容
随时随地看视频慕课网APP