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



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

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

这是我的函数,仅使用包含两者的输入 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;
}

使用CancellationTokenSourceTask.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(),以使程序运行足够长的时间,以使演示有意义。

相关内容

最新更新