【问题标题】:is there a way to cancel it when your program is waiting for a user input [duplicate]当您的程序等待用户输入时,有没有办法取消它[重复]
【发布时间】:2020-04-29 12:19:44
【问题描述】:

我是一名初学者程序员,我想知道是否有办法做到这一点,理想情况下我会拥有它,这样它只要求输入 5 秒,如果没有按下任何内容,则取消并继续前进需要一个单独的线程吗?,有没有办法在 C# 中做这样的事情?还是这只是使用控制台的限制?

【问题讨论】:

    标签: c#


    【解决方案1】:

    你可以使用

    string input = string.Empty;
    var task = Task.Run(() => input = Console.ReadLine());
    if(task.Wait(TimeSpan.FromSeconds(5)))
    {
        Console.WriteLine($"Value Read {input}");
    }
    else
    {
        Console.WriteLine("You are timed out");
    }
    

    Task.Wait 在超时之前等待指定的 TimeSpan 持续时间以完成任务。

    【讨论】:

      猜你喜欢
      • 2020-03-17
      • 1970-01-01
      • 1970-01-01
      • 2021-01-01
      • 2022-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-31
      相关资源
      最近更新 更多