Task ContinueWith


前正無生意,且記Task.ContinueWith之用法。

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("主線程開始");
            Task<string> task = Task<string>.Run(() => {
                Thread.Sleep(2000);
                return Thread.CurrentThread.ManagedThreadId.ToString();
            });

            task.GetAwaiter().OnCompleted(() =>
            {
                Console.WriteLine(task.Result);
            });
            //ContonieWith會在task上一個任務執行完畢之后,繼續執行新的任務
            task.ContinueWith(m => { Console.WriteLine("第一個任務結束啦!我是第二個任務"); });
            Console.WriteLine("主線程結束");
            Console.Read();
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM