如何修改Identify函数实现指纹认证与按键取消的互斥等待?
解决方案:同时监听指纹认证与按键取消输入
Got it, let's solve this problem where we need to wait for either a fingerprint input for authentication OR a key press to cancel the process. Here's how to modify your Identify function to handle both operations in parallel, with one triggering the cancellation of the other as soon as it completes.
Modified Code
using System.Threading; using System.Threading.Tasks; public static bool Identify(out FingerId identity) { identity = default; var cancellationTokenSource = new CancellationTokenSource(); bool wasInterruptedByKeyPress = false; // Task 1: Run fingerprint authentication (supports cancellation) var fingerprintTask = Task.Run(() => { try { // Replace with your actual FingerBio.Identify call // If your FingerBio API accepts a CancellationToken, pass it here bool authSuccess = FingerBio.Identify(out identity, cancellationTokenSource.Token); return authSuccess; } catch (OperationCanceledException) { // Authentication was canceled by key press return false; } }, cancellationTokenSource.Token); // Task 2: Listen for any key press to cancel authentication var keyPressTask = Task.Run(() => { Console.Write("Enter any key to cancel. "); Console.ReadKey(true); // 'true' hides the pressed key from console output wasInterruptedByKeyPress = true; cancellationTokenSource.Cancel(); // Cancel the fingerprint task immediately return true; }, cancellationTokenSource.Token); // Wait for the first task to finish (either fingerprint auth completes or key is pressed) var completedTask = Task.WhenAny(fingerprintTask, keyPressTask).Result; // Clean up: Ensure both tasks are properly canceled/finished to avoid resource leaks cancellationTokenSource.Cancel(); Task.WaitAll(fingerprintTask, keyPressTask); // Handle the result if (wasInterruptedByKeyPress) { Console.WriteLine("\nFingerprint authentication canceled."); return false; } return fingerprintTask.Result; }
Key Details & Notes
- Cancellation Token: We use
CancellationTokenSourceto create a cancelable context. When either task finishes, it cancels the other task to stop unnecessary work immediately. - Fingerprint Task Adjustment: If your
FingerBio.Identifymethod doesn't natively support cancellation tokens, you'll need to tweak the logic—for example, add periodic checks ofcancellationTokenSource.Token.IsCancellationRequestedinside any loops in the fingerprint process to exit early. - Key Press Behavior:
Console.ReadKey(true)prevents the pressed key from being displayed in the console, keeping the output clean. Remove thetrueparameter if you want to show the key the user pressed. - Cleanup: Always call
Cancel()andWaitAll()to ensure no background threads are left hanging, which could cause memory leaks or unexpected behavior. - Exception Handling: We catch
OperationCanceledExceptionto gracefully handle cases where the fingerprint task is canceled by the key press, avoiding unhandled exceptions.
内容的提问来源于stack exchange,提问作者Administrator
相关产品推荐
相关产品推荐

