为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
倚天杖 2023-04-29 09:55:22
我正在学习套接字消息传递。我在 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' 很长时间。
查看完整描述

1 回答

?
翻阅古今

TA贡献1780条经验 获得超5个赞

问题出在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);在当前正在制作新功能的地方调用。


注意:此答案不适用于最佳实践,但会得到一个原型来工作。


查看完整回答
反对 回复 2023-04-29
  • 1 回答
  • 0 关注
  • 72 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信