首頁 > 軟體

C#使用Task.ContinueWith組合任務

2022-04-20 22:00:21

程式碼案例

簡單Demo

程式碼:

        public static void Main()
        {
            //建立一個任務
            Task<int> task = new Task<int>(() =>
            {
                int sum = 0;
                Console.WriteLine("使用Task非同步執行操作.");
                for (int i = 0; i <= 100; i++)
                {
                    sum += i;
                }
                return sum;
            });
            
            //啟動任務,並安排到當前任務佇列執行緒中執行任務(System.Threading.Tasks.TaskScheduler)
            task.Start();
            Console.WriteLine("主執行緒執行其他程式.");
           
            //任務完成時執行處理。
            Task cwt = task.ContinueWith(t =>
            {
                Console.WriteLine("任務完成後的結果是:{0}", t.Result.ToString());
            });
            task.Wait();
            cwt.Wait();
            Console.ReadLine();
            Console.ReadKey();
        }

結果:

任務的序列

程式碼:

        static void Main(string[] args)
        {
            ConcurrentStack<int> stack = new ConcurrentStack<int>();

            //t1先序列
            var t1 = Task.Factory.StartNew(() =>
            {
                //入棧
                stack.Push(1);
                stack.Push(2);
            });

            //t2,t3並行執行
            var t2 = t1.ContinueWith(t =>
            {
                int result;
                //出棧
                stack.TryPop(out result);
                Console.WriteLine("Task t2 result={0},Thread id {1}", result, Thread.CurrentThread.ManagedThreadId);
            });

            //t2,t3並行執行
            var t3 = t1.ContinueWith(t =>
            {
                int result;
                //出棧
                stack.TryPop(out result);
                Console.WriteLine("Task t3 result={0},Thread id {1}", result, Thread.CurrentThread.ManagedThreadId);
            });

            //等待t2和t3執行完
            Task.WaitAll(t2, t3);

            //t7序列執行
            var t4 = Task.Factory.StartNew(() =>
            {
                Console.WriteLine("當前的集合數目:{0},Thread id {1}", stack.Count, Thread.CurrentThread.ManagedThreadId);
            });
            t4.Wait();
            Console.ReadKey();
        }

結果:

子任務

程式碼:

        public static void Main()
        {
            Task<string[]> parent = new Task<string[]>(state =>
            {
                Console.WriteLine(state);
                string[] result = new string[2];
                //建立並啟動子任務
                new Task(() => { result[0] = "我是子任務1。"; }, TaskCreationOptions.AttachedToParent).Start();
                new Task(() => { result[1] = "我是子任務2。"; }, TaskCreationOptions.AttachedToParent).Start();
                return result;
            }, "我是父任務,並在處理過程中創建多個子任務,所有的子任務完成以後我才會開始執行。");           
            //任務處理完成後執行的操作
            parent.ContinueWith(t =>
            {
                Array.ForEach(t.Result, r => Console.WriteLine(r));
            });
            //啟動父任務
            parent.Start();
            //等待任務結束 Wait只能等待父執行緒結束,沒辦法等到父執行緒的ContinueWith結束
            //parent.Wait();
            Console.ReadLine();
        }

結果:

動態並行

程式碼:

    class Node
    {
        public Node Left { get; set; }
        public Node Right { get; set; }
        public string Text { get; set; }
    }
    class Program
    {
        static Node GetNode()
        {
            Node root = new Node
            {
                Left = new Node
                {
                    Left = new Node
                    {
                        Text = "L-L"
                    },
                    Right = new Node
                    {
                        Text = "L-R"
                    },
                    Text = "L"
                },
                Right = new Node
                {
                    Left = new Node
                    {
                        Text = "R-L"
                    },
                    Right = new Node
                    {
                        Text = "R-R"
                    },
                    Text = "R"
                },
                Text = "Root"
            };
            return root;
        }

        static void Main(string[] args)
        {
            Node root = GetNode();
            DisplayTree(root);
        }

        static void DisplayTree(Node root)
        {
            var task = Task.Factory.StartNew(() => DisplayNode(root),
                                            CancellationToken.None,
                                            TaskCreationOptions.None,
                                            TaskScheduler.Default);
            task.Wait();
        }

        static void DisplayNode(Node current)
        {

            if (current.Left != null)
                Task.Factory.StartNew(() => DisplayNode(current.Left),
                                            CancellationToken.None,
                                            TaskCreationOptions.AttachedToParent,
                                            TaskScheduler.Default);
            if (current.Right != null)
                Task.Factory.StartNew(() => DisplayNode(current.Right),
                                            CancellationToken.None,
                                            TaskCreationOptions.AttachedToParent,
                                            TaskScheduler.Default);
            Console.WriteLine("當前節點值:{0};處理的Thread ID ={1}", current.Text, Thread.CurrentThread.ManagedThreadId);
        }
    }

結果:

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


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