c# - 等待两个 "user input"任务中的一个完成,中止另一个

标签 c# task user-input fingerprint

基本上我需要等待两个输入。

  1. 从指纹传感器接收指纹以进行身份​​验证
  2. 接收用于取消指纹认证的用户 key 输入

这是我的函数,仅使用 应该 包含两者的输入 No.1:

public static bool Identify(out FingerId identity)
{
    bool interrupted = false; // should be changed if user entered key and not finger

    Console.Write("Enter any key to cancel. ");
    // Should run along with "Console.ReadKey()"
    FingerBio.Identify(_session, out Finger._identity);

    identity = Finger._identity;
    return interrupted;
}

最佳答案

使用 CancellationTokenSource连同 Task.WhenAny .

由于您的问题没有很多关于您的用户界面任务的详细信息,这里是一个具有模式一般意义的演示。

该演示使用 Task.Run(...) 模拟您的用户界面任务。第二个任务通过使用无限循环模拟长时间运行的任务。当第一个任务完成时,我们将取消第二个任务。

https://dotnetfiddle.net/8usHLX

public class Program
{
    public async Task Identify() 
    {
        var cts = new CancellationTokenSource();
        var token = cts.Token;

        var task1 = Task.Run(async () => {
            await Task.Delay(1000);
            Console.WriteLine("Task1");
        }, token);

        var task2 = Task.Run(async () => {
            while (true) {
                Console.WriteLine("Task2");
                await Task.Delay(1000);
            }
        }, token);

        // When one of them completes, cancel the other.        
        // Try commenting out the cts.Cancel() to see what happens.
        await Task.WhenAny(task1, task2);
        cts.Cancel();
    }

    public static void Main()
    {
        var p = new Program();
        p.Identify().GetAwaiter().GetResult();
        Task.Delay(5000);
    }
}

Main() 方法在末尾有一个 Task.Delay() 以保持程序运行足够长的时间以使演示有意义。

关于c# - 等待两个 "user input"任务中的一个完成,中止另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49929040/

相关文章:

c# - 任务不包含 Run 方法的定义

c# - 无法在 .NET FX4.6 上的 .NET Standard2.0 库中使用 System.Configuration.Configuration 管理器

c# - 将字符串通用解析为 float

c# - 新库中的异步与非异步方法

unit-testing - 通过多次传递输入来测试函数

bash - "Read"bash 脚本中的命令被跳过

java - do while 循环和用户输入问题

c# - Sharepoint 开发教程

c# - 在 ASP.NET 中设置 DropDownList 的值

c# - 任务 IsCanceled 是假的,而我取消了