works:programmer:cs:async-await-and-task
Async, Await and Task in C#
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; public class Program { public Program() { List<Task<String>> tasks = new List<Task<String>>(); tasks.Add(this.getNameAsync()); tasks.Add(this.getSurenameAsync()); tasks.Add(this.getAgeAsync()); try { Task.WaitAll(tasks.ToArray()); } catch (AggregateException) {} for (var ctr = 0 ; ctr < tasks.Count; ctr++) { if (tasks[ctr].Status == TaskStatus.Faulted) Console.WriteLine("{0} does not exist", tasks[ctr]); else Console.WriteLine("{0} in '{1}'", tasks[ctr].Result, tasks[ctr]); } //var name = this.getNameAsync(); //name.Wait(); //Console.WriteLine(name.Result); } public async Task<string> getNameAsync() { Thread.Sleep(1000); return "The name"; } public async Task<string> getSurenameAsync() { Thread.Sleep(2000); return "The surename"; } public async Task<string> getAgeAsync() { return await this.getRealAgeAsync(); } public async Task<string> getRealAgeAsync() { Thread.Sleep(3000); return "The age"; } public static void Main() { new Program(); Console.WriteLine("Hello World"); } }
works/programmer/cs/async-await-and-task.txt · Последнее изменение: 2021/04/13 13:02 — 127.0.0.1