异步任务取消、超时
一、定义异步任务
//定义异步任务 public class AsyncClass { public static async Task TaskAsync(CancellationToken token) { token.Register(() => { Console.WriteLine("TaskAsync被取消"); }); for (int i = 0; i < 10; i++) { if (token.IsCancellationRequested) { token.ThrowIfCancellationRequested(); } await Task.Delay(1000); Console.WriteLine($"TaskAsync:{i}"); } } public static async Task TaskAsync1(CancellationToken token) { token.Register(() => { Console.WriteLine("TaskAsync1 is Cancel"); }); for (int i = 0; i < 10; i++) { if (token.IsCancellationRequested) { token.ThrowIfCancellationRequested(); } await Task.Delay(1000); Console.WriteLine($"TaskAsync1:{i}"); } } }
二、实现异步任务取消
#region 取消 var cts = new CancellationTokenSource(); try { var token = cts.Token; token.Register(() => { Console.WriteLine("Main 被取消"); });//当前线程取消提示 cts.CancelAfter(3000);//3秒后取消 //cts.Cancel(); await AsyncClass.TaskAsync(token); } catch (OperationCanceledException ex) { Console.WriteLine(ex.ToString()); } catch (TimeoutException ex) { Console.WriteLine(ex.ToString()); } finally { cts.Dispose(); } #endregion
三、实现异步任务超时
#region 超时 var TimeOutCts = new CancellationTokenSource(); try { var TimeOutToken = TimeOutCts.Token; //方式一 //var mytask = AsyncClass.TaskAsync(TimeOutToken); //var completedTask = await Task.WhenAny(mytask, Task.Delay(2000, TimeOutToken)); //if (completedTask != mytask) //{ // throw new TimeoutException("TaskAsync超时了");//手动抛出超时异常 //} //方式二 await AsyncClass.TaskAsync1(TimeOutToken).WaitAsync(TimeSpan.FromMilliseconds(2000)); } catch (TimeoutException ex) { TimeOutCts.Cancel();//捕获超时异常,取消任务 Console.WriteLine(ex.ToString()); } catch (OperationCanceledException ex) { Console.WriteLine(ex.ToString()); } finally { TimeOutCts.Dispose(); } #endregion
四、运行结果
喜欢 C#、SQL、Web