亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 123 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號