# concurrency **Repository Path**: diywindow/concurrency ## Basic Information - **Project Name**: concurrency - **Description**: 并发、异步、同步、async、await - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 1 - **Created**: 2016-10-10 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README async和await --------------- 使用async后面一定会加Task<实体对象> await会将Task<实体对象>里的“实体对象”提取出来返回。 等待一组任务完成 --------------- ``` public async Task IndexAsync() { var firstTask = getTaskInt(1); var thireTask = getTaskInt(3); var secondTask = getTaskInt(2); var tasks = new[] { firstTask, thireTask, secondTask }; await Task.WhenAll(tasks); int firstVal = firstTask.Result; int secondVal = secondTask.Result; int thireVal = thireTask.Result; } private static async Task getTaskInt(int val) { await Task.Delay(TimeSpan.FromSeconds(val)); return val; } //或者: public async Task Index() { //Services.FeedService feedService = new Services.FeedService(); Stopwatch timer = Stopwatch.StartNew(); timer.Start(); var feeds = await GetFeeds(); timer.Stop(); feeds.TimeTaken = timer.ElapsedMilliseconds; return View(feeds); } public async Task GetFeeds() { var emails = new HttpClient().GetStringAsync("http://localhost:18545/api/Emails"); var myTasks = new HttpClient().GetStringAsync("http://localhost:18545/api/Tasks"); var notes = new HttpClient().GetStringAsync("http://localhost:18545/api/Notes"); var bookmarks = new HttpClient().GetStringAsync("http://localhost:18545/api/Bookmarks"); await Task.WhenAll(emails, myTasks, notes, bookmarks); Dashboard dash = new Dashboard(); dash.Emails = Deserialize(emails.Result); dash.Bookmarks = Deserialize(bookmarks.Result); dash.Notes = Deserialize(notes.Result); dash.Tasks = Deserialize(myTasks.Result); return dash; } ``` //await Task.Delay(1000).ConfigureAwait(false); ConfigureAwait(false)的作用是await执行完后,下一行代码使用新线程执行,如果await上一行代码的上下文是UI线程, 不添加ConfigureAwait(false),await执行完后,下一行代码继续使用UI线程。