日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > asp.net >内容正文

asp.net

.Net 多线程 异步编程 Await、Async和Task

發(fā)布時(shí)間:2025/3/15 asp.net 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 .Net 多线程 异步编程 Await、Async和Task 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

await和async簡(jiǎn)介

??await和async是在C#5中引入,并且在.NetFramewor4.5以及.NetCore中進(jìn)行了支持。主要是解決性能瓶頸,并且增強(qiáng)系統(tǒng)的響應(yīng)能力。

msdn關(guān)于await以及async運(yùn)行機(jī)理的描述

以上demo詳細(xì)的描述了使用await時(shí)程序的運(yùn)行機(jī)制,需要注意的以下幾點(diǎn):

  • 第五步:執(zhí)行完成后如果發(fā)現(xiàn)下一步還有await即設(shè)置了中斷點(diǎn),此時(shí)命令會(huì)直接跳出此方法即執(zhí)行6,換句話(huà)說(shuō),await表達(dá)式執(zhí)行時(shí)暫停并不構(gòu)成方法退出,只會(huì)導(dǎo)致 finally 代碼塊不運(yùn)行
  • 第七步:當(dāng)執(zhí)行當(dāng)getStringTask返回結(jié)果(第七步)及await等待方法執(zhí)行完成開(kāi)始執(zhí)行后續(xù)操作時(shí)(8)此時(shí)的線程已經(jīng)和第四步執(zhí)行的線程不同編號(hào)了,但是此時(shí)4所在線程上下文中的AsyncLocal變量會(huì)被復(fù)制到await返回后的線程上下文中。詳細(xì)參照https://www.cnblogs.com/liyong-blackStone/p/10270526.html
  • async 和 await 關(guān)鍵字不會(huì)創(chuàng)建其他線程。 因?yàn)楫惒椒椒ú粫?huì)在其自身線程上運(yùn)行,因此它不需要多線程.

Task簡(jiǎn)介

Task類(lèi)的表示單個(gè)操作不會(huì)返回一個(gè)值,通常以異步方式執(zhí)行Task對(duì)象是一種的中心思想基于任務(wù)的異步模式。首次引入.NET Framework 4 中。
Task可以通過(guò)以下幾種方式開(kāi)始執(zhí)行:

Task.Run(() =>{Console.WriteLine("無(wú)返回值委托");});Task.Run<int>(() =>{Console.WriteLine("帶返回值委托");return 1;});Task t = new Task(() =>{Console.WriteLine("聲明一個(gè)Task可以后續(xù)通過(guò)t.run執(zhí)行");});TaskFactory factory = new TaskFactory();factory.StartNew<int>(() =>{Console.WriteLine("通過(guò)TaskFactory執(zhí)行");return 1;});Task t4 = new Task(() =>{Console.WriteLine("同步執(zhí)行");});// 同步執(zhí)行t4.RunSynchronously();

task的執(zhí)行方式這里不多做介紹,下面主要說(shuō)下Task的異常處理。

異步方法內(nèi)部的異常處理

.Net中異步方法由 async修飾符標(biāo)記,通常包含一個(gè)或多個(gè)await表達(dá)式或語(yǔ)句。await表達(dá)式將await運(yùn)算符應(yīng)用于 Task 或Task。由于在異步方法中通常會(huì)存在多個(gè)線程,而子線程中的異常信息不能自動(dòng)的拋到主線程上,所以要想在主線程上獲得子線程的異常信息,需要借助于返回的task這個(gè)對(duì)象。以下為Msdn給出的一段示例代碼:

public async Task DoSomethingAsync() {Task<string> theTask = DelayAsync();try{string result = await theTask;Debug.WriteLine("Result: " + result);}catch (Exception ex){Debug.WriteLine("Exception Message: " + ex.Message);}Debug.WriteLine("Task IsCanceled: " + theTask.IsCanceled);Debug.WriteLine("Task IsFaulted: " + theTask.IsFaulted);if (theTask.Exception != null){Debug.WriteLine("Task Exception Message: "+ theTask.Exception.Message);Debug.WriteLine("Task Inner Exception Message: "+ theTask.Exception.InnerException.Message);} }private async Task<string> DelayAsync() {await Task.Delay(100);// Uncomment each of the following lines to// demonstrate exception handling.//throw new OperationCanceledException("canceled");//throw new Exception("Something happened.");return "Done"; }// Output when no exception is thrown in the awaited method: // Result: Done // Task IsCanceled: False // Task IsFaulted: False// Output when an Exception is thrown in the awaited method: // Exception Message: Something happened. // Task IsCanceled: False // Task IsFaulted: True // Task Exception Message: One or more errors occurred. // Task Inner Exception Message: Something happened.// Output when a OperationCanceledException or TaskCanceledException // is thrown in the awaited method: // Exception Message: canceled // Task IsCanceled: True // Task IsFaulted: False

對(duì)于異步線程的執(zhí)行結(jié)果,最多有三種情況

  • 正常執(zhí)行結(jié)束:可以通過(guò)IsCompletedSuccessfully 屬性表示任務(wù)正常結(jié)束,并成功執(zhí)行。特別說(shuō)明:IsCompleted為true只能表示執(zhí)行完成,當(dāng)任務(wù)處于三種最終狀態(tài)之一: RanToCompletion, Faulted,或Canceled。時(shí)他都為true
  • 發(fā)生異常:發(fā)生異常時(shí),可以通過(guò)返回的task對(duì)象中的IsFaulted屬性判斷,為true時(shí)表示發(fā)生異常,如果要獲取具體的異常信息,可以通過(guò)以下以下方式獲取
task.Exception.InnerException.Message
  • 異步線程被取消:異步線程被取消時(shí)task中的IsCanceled屬性會(huì)被設(shè)置為true
    了解取消任務(wù)可以參考msdn示例:
using System; using System.Threading; using System.Threading.Tasks;public class Example {public static void Main(){// Create a cancellation token and cancel it.var source1 = new CancellationTokenSource();var token1 = source1.Token;source1.Cancel();// Create a cancellation token for later cancellation.var source2 = new CancellationTokenSource();var token2 = source2.Token;// Create a series of tasks that will complete, be cancelled, // timeout, or throw an exception.Task[] tasks = new Task[12];for (int i = 0; i < 12; i++){switch (i % 4) {// Task should run to completion.case 0:tasks[i] = Task.Run(() => Thread.Sleep(2000));break;// Task should be set to canceled state.case 1: tasks[i] = Task.Run( () => Thread.Sleep(2000),token1);break; case 2:// Task should throw an exception.tasks[i] = Task.Run( () => { throw new NotSupportedException(); } );break;case 3:// Task should examine cancellation token.tasks[i] = Task.Run( () => { Thread.Sleep(2000); if (token2.IsCancellationRequested)token2.ThrowIfCancellationRequested();Thread.Sleep(500); }, token2); break;}}Thread.Sleep(250);source2.Cancel();try {Task.WaitAll(tasks);}catch (AggregateException ae) {Console.WriteLine("One or more exceptions occurred:");foreach (var ex in ae.InnerExceptions)Console.WriteLine(" {0}: {1}", ex.GetType().Name, ex.Message);} Console.WriteLine("\nStatus of tasks:");foreach (var t in tasks) {Console.WriteLine(" Task #{0}: {1}", t.Id, t.Status);if (t.Exception != null) {foreach (var ex in t.Exception.InnerExceptions)Console.WriteLine(" {0}: {1}", ex.GetType().Name,ex.Message);}}} } // The example displays output like the following: // One or more exceptions occurred: // TaskCanceledException: A task was canceled. // NotSupportedException: Specified method is not supported. // TaskCanceledException: A task was canceled. // TaskCanceledException: A task was canceled. // NotSupportedException: Specified method is not supported. // TaskCanceledException: A task was canceled. // TaskCanceledException: A task was canceled. // NotSupportedException: Specified method is not supported. // TaskCanceledException: A task was canceled. // // Status of tasks: // Task #13: RanToCompletion // Task #1: Canceled // Task #3: Faulted // NotSupportedException: Specified method is not supported. // Task #8: Canceled // Task #14: RanToCompletion // Task #4: Canceled // Task #6: Faulted // NotSupportedException: Specified method is not supported. // Task #7: Canceled // Task #15: RanToCompletion // Task #9: Canceled // Task #11: Faulted // NotSupportedException: Specified method is not supported. // Task #12: Canceled

轉(zhuǎn)載于:https://www.cnblogs.com/liyong-blackStone/p/10276769.html

總結(jié)

以上是生活随笔為你收集整理的.Net 多线程 异步编程 Await、Async和Task的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。