1、C#异步简介
C#使用关键字await实现async异步操作,需要在await关键字后面添加异步代码或者等待代码。如果要优雅的取消异步方法,则需要使用CancellationToken来检测任务是否取消。
2、代码示例
using System; using System.Threading; using System.Threading.Tasks; namespace ConsoleApplication { class Program { static void Main() { Console.WriteLine($@"{DateTime.Now:yyyy-MM-dd HH:mm:ss fff} Start Process."); var tokenSource = new CancellationTokenSource(); TestAsync(tokenSource.Token, 1500).GetAwaiter(); Thread.Sleep(4000); tokenSource.Cancel(); Console.WriteLine($@"{DateTime.Now:yyyy-MM-dd HH:mm:ss fff} Stop Process."); } private static async Task TestAsync(CancellationToken token, int interval) { Console.WriteLine($@"{DateTime.Now:yyyy-MM-dd HH:mm:ss fff} Start TestAsync."); var number = 0; while (true) { try { //异步延时 await Task.Delay(interval, token); } catch (Exception) { break; } if (token.IsCancellationRequested) { break; } Console.WriteLine($@"{DateTime.Now:yyyy-MM-dd HH:mm:ss fff} Current number: {++number}."); } Console.WriteLine($@"{DateTime.Now:yyyy-MM-dd HH:mm:ss fff} Stop TestAsync."); } } }
3、运行截图