C# 异步编程
C# async/await特性可以创建b并使用异步方法
await表达式
await表达式指定了一个异步执行的任务
取消一个异步操作
CancellationTokenSource和CancellationToken来实现取消操作。
调用CancellationTokenSource的Cancel时,它本身不会执行取消操作。而是会将CancellationToken的IsCancellationRequest属性设置为true。
class Program { static void Main(string[] args) { CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken token = cts.Token; MyClass my = new MyClass(); Task t = my.RunAsync(token); Thread.Sleep(3000); // cts.Cancel(); //Console.ReadKey(); t.Wait(); Console.WriteLine("Was Cancelled:{0}", token.IsCancellationRequested); Console.ReadKey(); } }
class MyClass { internal async Task RunAsync(CancellationToken token) { if (token.IsCancellationRequested) { return; } await Task.Run(() => CycleMethod(token), token); } void CycleMethod(CancellationToken ct) { Console.WriteLine("Starting CycleMethod"); const int Max = 5; for (int i = 0; i < Max; i++) { if (ct.IsCancellationRequested) { return; } // Thread.Sleep(1000); Console.WriteLine(" {0} of {1} iterations completed", i + 1, Max); } } }
在调用方法中同步等待任务
class MydownLoadString { Stopwatch sw = new Stopwatch(); public void DoRun() { const int LargeNumber = 60000000; sw.Start(); Task<int> t1 = CountCharactersAsync(1, "http://www.microsoft.com"); Task<int> t2 = CountCharactersAsync(2, "http://www.baidu.com"); //Task<int>[] tasks = new Task<int>[] { t1, t2 }; //Task.WaitAll(tasks); //Task.WaitAny(tasks); Console.WriteLine("Task 1: {0}Finished",t1.IsCompleted ? "" : "Not"); Console.WriteLine("Task 2: {0}Finished", t2.IsCompleted ? "" : "Not"); Console.ReadKey(); } private async Task<int> CountCharactersAsync(int id, string site) { WebClient wc = new WebClient(); // Console.WriteLine("Starting call {0} : {1:4}ms", id, sw.Elapsed.TotalMilliseconds); string result = await wc.DownloadStringTaskAsync(new Uri(site)); Console.WriteLine(" Call {0} completed: {1:4} ms", id, sw.Elapsed.TotalMilliseconds); return result.Length; } private void CountToALargeNumber(int id, int value) { for (long i = 0; i < value; i++) ; Console.WriteLine(" End counting{0} : {1:4} ms", id, sw.Elapsed.TotalMilliseconds); } }
//Task<int>[] tasks = new Task<int>[] { t1, t2 };
//Task.WaitAll(tasks);
把上面两行注销掉
若
//Task<int>[] tasks = new Task<int>[] { t1, t2 }; //Task.WaitAny(tasks);
把上面两行注销了
WaitAll方法,这时代码会停止并等待任务全部完成,然后继续执行
WaitAny方法 将终止并等待至少一个任务完成
在异步方法中异步地等待任务
例子:
class Program { static void Main(String[] args) { MydownLoadString m = new MydownLoadString(); m.DoRun(); Console.ReadKey(); } } class MydownLoadString { Stopwatch sw = new Stopwatch(); public void DoRun() { Task<int> t = CountCharacterAsync("http://www.microsoft.com", "http://www.baidu.com"); Console.WriteLine("DoRun: Task {0}Finished", t.IsCompleted ? "" : "Not "); Console.WriteLine("DoRun: Result = {0}", t.Result); } private async Task<int> CountCharacterAsync(string site1, string site2) { WebClient wc1 = new WebClient(); WebClient wc2 = new WebClient(); Task<string> t1 = wc1.DownloadStringTaskAsync(new Uri(site1)); Task<string> t2 = wc2.DownloadStringTaskAsync(new Uri(site2)); List<Task<string>> tasks = new List<Task<string>>(); tasks.Add(t1); tasks.Add(t2); await Task.WhenAll(tasks); Console.WriteLine("Task 1: {0}Finished", t1.IsCompleted ? "" : "Not"); Console.WriteLine("Task 2: {0}Finished", t2.IsCompleted ? "" : "Not"); return t1.IsCompleted ? t1.Result.Length : t2.Result.Length; }
Task.WhenAny组合子会异步地等待与之相关的某个Task完成,若上面的Task.WhenAll 换成Task.WhenAny 则
Task.Delay()
Task.Delay方法创建一个Task对象,可以将暂停其对象在子线程中的处理,并在一定时间完成,与Thread.Sleep阻塞线程不同,Task.Delay不会阻塞线程,线程可以继续完成处理其他工作