标签:部分 key 发布者 wait sdn oid csharp value complete
原文:【你不一定知晓的】C#取消异步操作在.Net和C#中运行异步代码相当简单,因为我们有时候需要取消正在进行的异步操作,通过本文,可以掌握 通过CancellationToken取消任务(包括non-cancellable任务)。
private void BackgroundLongRunningTask(object sender, DoWorkEventArgs e) { BackgroundWorker worker = (BackgroundWorker)sender; for (int i = 1; i <= 10000; i++) { if (worker.CancellationPending == true) { e.Cancel = true; break; } // Do something } }
已经不再推荐这种方式来完成异步和长时间运行的操作,但是大部分概念在现在依旧可以使用。
/// <summary> /// Compute a value for a long time. /// </summary> /// <returns>The value computed.</returns> /// <param name="loop">Number of iterations to do.</param> private static Task<decimal> LongRunningOperation(int loop) { // Start a task and return it return Task.Run(() => { decimal result = 0; // Loop for a defined number of iterations for (int i = 0; i < loop; i++) { // Do something that takes times like a Thread.Sleep in .NET Core 2. Thread.Sleep(10); result += i; } return result; }); } // 这里我们使用Thread.Sleep 模仿长时间运行的操作
简单异步调用代码:
public static async Task ExecuteTaskAsync() { Console.WriteLine(nameof(ExecuteTaskAsync)); Console.WriteLine("Result {0}", await LongRunningOperation(100)); Console.WriteLine("Press enter to continue"); Console.ReadLine(); }
/// <summary> /// Compute a value for a long time. /// </summary> /// <returns>The value computed.</returns> /// <param name="loop">Number of iterations to do.</param> /// <param name="cancellationToken">The cancellation token.</param> private static Task<decimal> LongRunningCancellableOperation(int loop, CancellationToken cancellationToken) { Task<decimal> task = null; // Start a task and return it task = Task.Run(() => { decimal result = 0; // Loop for a defined number of iterations for (int i = 0; i < loop; i++) { // Check if a cancellation is requested, if yes, // throw a TaskCanceledException. if (cancellationToken.IsCancellationRequested) throw new TaskCanceledException(task); // Do something that takes times like a Thread.Sleep in .NET Core 2. Thread.Sleep(10); result += i; } return result; }); return task; }
// 以下代码 利用 CancellationSource默认构造函数 完成超时取消 public static async Task ExecuteTaskWithTimeoutAsync(TimeSpan timeSpan) { Console.WriteLine(nameof(ExecuteTaskWithTimeoutAsync)); using (var cancellationTokenSource = new CancellationTokenSource(timeSpan)) { try { var result = await LongRunningCancellableOperation(500, cancellationTokenSource.Token); Console.WriteLine("Result {0}", result); } catch (TaskCanceledException) { Console.WriteLine("Task was cancelled"); } } Console.WriteLine("Press enter to continue"); Console.ReadLine(); }
public static async Task ExecuteManuallyCancellableTaskAsync() { Console.WriteLine(nameof(ExecuteManuallyCancellableTaskAsync)); using (var cancellationTokenSource = new CancellationTokenSource()) { // Creating a task to listen to keyboard key press var keyBoardTask = Task.Run(() => { Console.WriteLine("Press enter to cancel"); Console.ReadKey(); // Cancel the task cancellationTokenSource.Cancel(); }); try { var longRunningTask = LongRunningCancellableOperation(500, cancellationTokenSource.Token); var result = await longRunningTask; Console.WriteLine("Result {0}", result); Console.WriteLine("Press enter to continue"); } catch (TaskCanceledException) { Console.WriteLine("Task was cancelled"); } await keyBoardTask; } }
// 以上是一个控制台程序,异步接收控制台输入,发出取消命令。
private static async Task<decimal> LongRunningOperationWithCancellationTokenAsync(int loop, CancellationToken cancellationToken) { // We create a TaskCompletionSource of decimal var taskCompletionSource = new TaskCompletionSource<decimal>(); // Registering a lambda into the cancellationToken cancellationToken.Register(() => { // We received a cancellation message, cancel the TaskCompletionSource.Task taskCompletionSource.TrySetCanceled(); }); var task = LongRunningOperation(loop); // Wait for the first task to finish among the two var completedTask = await Task.WhenAny(task, taskCompletionSource.Task); return await completedTask; }
像上面代码一样执行取消命令 :
public static async Task CancelANonCancellableTaskAsync() { Console.WriteLine(nameof(CancelANonCancellableTaskAsync)); using (var cancellationTokenSource = new CancellationTokenSource()) { // Listening to key press to cancel var keyBoardTask = Task.Run(() => { Console.WriteLine("Press enter to cancel"); Console.ReadKey(); // Sending the cancellation message cancellationTokenSource.Cancel(); }); try { // Running the long running task var longRunningTask = LongRunningOperationWithCancellationTokenAsync(100, cancellationTokenSource.Token); var result = await longRunningTask; Console.WriteLine("Result {0}", result); Console.WriteLine("Press enter to continue"); } catch (TaskCanceledException) { Console.WriteLine("Task was cancelled"); } await keyBoardTask; } }
标签:部分 key 发布者 wait sdn oid csharp value complete
原文地址:https://www.cnblogs.com/lonelyxmas/p/10646655.html