首頁 > 軟體

C#連續任務Task.ContinueWith方法

2022-04-20 19:00:25

一、簡介

通過任務,可以指定在任務完成之後,應開始執行之後另一個特定任務。ContinueWith是Task根據其自身狀況,決定後續應該作何操作。也就是說,在執行完task後,會執行task.continuewith(XX)中的XX語句,但是是否執行、如何執行等需要看task的執行情況。例如:一個使用前一個任務的結果的新任務,如果前一個任務失敗了,這個任務就應執行一些清理工作。任務處理程式都不帶引數或者帶一個物件引數,而任務的連續處理方法都有一個Task型別的引數。

二、案例

案例一:

程式碼:

        static int TaskMethod(string name, int seconds)
        {
            Console.WriteLine("Frist Task Method : Task {0} is running on a thread id: {1}. Is thread pool thread: {2}",
            name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
            Thread.Sleep(TimeSpan.FromSeconds(seconds));
            return 60 * seconds;
        }
        static void Main(string[] args)
        {

            var FirstTask = new Task<int>(() => TaskMethod("Frist Task", 3));
            FirstTask.ContinueWith(t => Console.WriteLine("Frist Task Result: {0}. Thread id: {1}, Is in Thred Pool: {2}",
            t.Result, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread),
            TaskContinuationOptions.OnlyOnRanToCompletion);//執行緒池執行緒
            FirstTask.Start();
           
            Console.ReadKey();
        }

結果:

Start()和ContinueWith()的先後順序沒有關係,ContinueWith()會等待直到firstTask執行狀態達到 IsCompleted,因為TaskContinuationOptions中的OnlyOnRanToCompletion.必須指出的是,ContinueWith()中的引數是需要以Task為引數的,也就是firstTask作為引數被傳入,而且ContinueWith()執行線上程池中的執行緒中。我覺得比較重要的一點是:把ContinueWith()中的語句當做一塊新的語句塊,他們獨立於主執行緒。無論如何,他們都要被判斷,如果狀態(status)不滿足,那麼他們不執行;當指定了多個狀態,則使用合理的對應狀態。

案例二:

程式碼:

    class Program
    {
        static int TaskMethod(string name, int seconds)
        {
            Console.WriteLine("Task Method : Task {0} is running on a thread id: {1}. Is thread pool thread: {2}",
            name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
            Thread.Sleep(TimeSpan.FromSeconds(seconds));
            return 60 * seconds;
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Main Thread id {0}, Is in Thred Pool: {1}",
            Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);

            var firstTask = new Task<int>(() => TaskMethod("frist task", 3));
            var secondTask = new Task<int>(() => TaskMethod("second task", 2));

            firstTask.ContinueWith(t => Console.WriteLine("Result:Frist Thread Result: {0}. Thread id: {1}, Is in Thred Pool: {2}",
            t.Result, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread),
            TaskContinuationOptions.OnlyOnRanToCompletion);

            firstTask.Start();
            secondTask.Start();

            Thread.Sleep(TimeSpan.FromSeconds(4)); //給予足夠時間,讓firstTask、secondTask及其後續操作執行完畢。

            Task continuation = secondTask.ContinueWith(t => Console.WriteLine("Result:Second Thread Result: {0}. Thread id: {1}, Is in Thred Pool: {2}",
            t.Result, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread),
            TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously);
            Console.ReadLine();
            Console.ReadKey();
        }
    }

結果:

這裡主執行緒休眠了足足4秒鐘,足以讓firstTask和secondTask兩個任務完成執行,而後,由於secondTask的後續除了接受OnlyOnRanToCompletion外,還接受ExecuteSynchronously。因此,後續執行中,由於主執行緒還沒有結束,因此 ExecuteSynchronously得到認可,故secondTask的後續是在主執行緒上執行。

案例三:

程式碼:

    class Program
    {
        static int TaskMethod(string name, int seconds)
        {
            Console.WriteLine("Task Method : Task {0} is running on a thread id: {1}. Is thread pool thread: {2}",
            name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
            Thread.Sleep(TimeSpan.FromSeconds(seconds));
            return 60 * seconds;
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Main Thread id {0}, Is in Thred Pool: {1}",
            Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);

            var firstTask = new Task<int>(() => TaskMethod("frist task", 3));
            var secondTask = new Task<int>(() => TaskMethod("second task", 2));

            firstTask.ContinueWith(t => Console.WriteLine("Result:Frist Thread Result: {0}. Thread id: {1}, Is in Thred Pool: {2}",
            t.Result, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread),
            TaskContinuationOptions.OnlyOnRanToCompletion);

            firstTask.Start();
            secondTask.Start();

           //Thread.Sleep(TimeSpan.FromSeconds(4)); //給予足夠時間,讓firstTask、secondTask及其後續操作執行完畢。

            Task continuation = secondTask.ContinueWith(t => Console.WriteLine("Result:Second Thread Result: {0}. Thread id: {1}, Is in Thred Pool: {2}",
            t.Result, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread),
            TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously);
            Console.ReadLine();
            Console.ReadKey();
        }
    }

結果:

然而,如果把4秒鐘的休眠註釋掉,那麼由於主執行緒很早就結束了,因此secondTask只能接受到OnlyOnRanToCompletion,因此還是執行線上程池中。

到此這篇關於C#連續任務Task.ContinueWith方法的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com