欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#中Task.ContinueWith連續(xù)任務(wù)使用實(shí)例

 更新時(shí)間:2022年02月14日 10:09:17   作者:廈門德仔  
本文主要介紹了C#中Task.ContinueWith連續(xù)任務(wù)使用實(shí)例,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

通過任務(wù),可以指定在任務(wù)完成之后,應(yīng)開始運(yùn)行之后另一個(gè)特定任務(wù)。例如,一個(gè)使用前一個(gè)任務(wù)的結(jié)果的新任務(wù),如果前一個(gè)任務(wù)失敗了,這個(gè)任務(wù)就應(yīng)執(zhí)行一些清理工作。任務(wù)處理程序都不帶參數(shù)或者帶一個(gè)對象參數(shù),而任務(wù)的連續(xù)處理方法都有一個(gè)Task類型的參數(shù),這里可以訪問起始任務(wù)的相關(guān)信息:

如下面的示例代碼: 

 ? class Program
? ? {
? ? ? ? static void DoOnFirst()
? ? ? ? {
? ? ? ? ? ? Console.WriteLine($"doing some task{Task.CurrentId}");
? ? ? ? ? ? Thread.Sleep(3000);
? ? ? ? }
? ? ? ? static void DoOnSecond(Task t)
? ? ? ? {
? ? ? ? ? ? Console.WriteLine($"task {t.Id} finished");
? ? ? ? ? ? Console.WriteLine($"this task id {Task.CurrentId}");
? ? ? ? ? ? Console.WriteLine("doing some cleanup");
? ? ? ? ? ? Thread.Sleep(3000);
? ? ? ? }
? ? ? ? static void Main(string[] args)
? ? ? ? {
? ? ? ? ? ? Task t1 = new Task(DoOnFirst);
? ? ? ? ? ? t1.Start();
? ? ? ? ? ??

? ? ? ? ? ? Task t2 = t1.ContinueWith(DoOnSecond);
? ? ? ? ? ? Task t3 = t1.ContinueWith(DoOnSecond);
? ? ? ? ? ? Task t4 = t2.ContinueWith(DoOnSecond);
? ? ? ? ? ? Console.ReadKey();
? ? ? ? }
? ? }
?

連續(xù)任務(wù)通過在任務(wù)上調(diào)用ContinueWith()方法來定義。也可以使用TaskFactory類來定義。t1.ContinueWith(DoOnSecond)方法表示,調(diào)用DoOnSecond()方法的新任務(wù)應(yīng)在任務(wù)t1結(jié)束時(shí)立即啟動(dòng)。在一個(gè)任務(wù)結(jié)束時(shí),可以啟動(dòng)多個(gè)任務(wù),連續(xù)任務(wù)也可以有另外一個(gè)連續(xù)任務(wù)。如下面的例子所示:

? ? ? ? ? ? Task t1 = new Task(DoOnFirst);
? ? ? ? ? ? t1.Start();? ? ? ? ? ??

? ? ? ? ? ? Task t2 = t1.ContinueWith(DoOnSecond);
? ? ? ? ? ? Task t3 = t1.ContinueWith(DoOnSecond);
? ? ? ? ? ? Task t4 = t2.ContinueWith(DoOnSecond);

使用TaskCreationOptions枚舉中的值,可以指定,連續(xù)的任務(wù)只有在起始任務(wù)成功(或者失敗)結(jié)束時(shí)啟動(dòng)。一些可能的值是OnlyOnFaulted、NotOnFaulted 、OnlyOnCanceled、NotOnCanceled和OnlyOnRanToCompletion。

Task t5 = t1.ContinueWith(DoOnError, TaskContinuationOptions.OnlyOnFaulted)

C# Task.ContinueWith 返回對象

使用Task.ContinueWith 可以在Task完成時(shí)而繼續(xù)執(zhí)行的邏輯

當(dāng)在ContinueWith中需要返回一個(gè)對象時(shí),應(yīng)該如何使用

 下方代碼可以表示,在設(shè)置緩存完成后,重新讀取緩存,并返回

?var item = await SetCacheItemAsync("key", ?cacheItems)
? ? ? ? ? ? ? ? .ContinueWith<>(async _ => await cacheItem.GetAsync(key));

到此這篇關(guān)于C#中Task.ContinueWith連續(xù)任務(wù)使用實(shí)例的文章就介紹到這了,更多相關(guān)C# Task.ContinueWith內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論