onlyou13

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
        private static void TestTask1()
        {
            Console.WriteLine("start TestTask1=====");
            Task task1 = new Task(() =>
            {
                Thread.Sleep(3000);
                Console.WriteLine($"..thread1 run..threadid={Thread.CurrentThread.ManagedThreadId}");
            });
            task1.Start();

            Task task2 = new Task(() =>
            {
                Thread.Sleep(2000);
                Console.WriteLine($"..thread2 run..threadid={Thread.CurrentThread.ManagedThreadId}");
            });
            task2.ContinueWith((o) => { Console.WriteLine($"thread2 finished.... threadid={Thread.CurrentThread.ManagedThreadId}"); });
            task2.Start();
            Console.WriteLine("end TestTask1=====");
        }

运行结果:

start TestTask1=====
end TestTask1=====
..thread2 run..threadid=5
thread2 finished.... threadid=6
..thread1 run..threadid=4
        private static void TestTask2()
        {
            Console.WriteLine("start TestTask2........");
            TaskFactory taskFactory = new TaskFactory();
            List<Task> tasks = new List<Task>();
            tasks.Add(taskFactory.StartNew(() =>
            {
                Thread.Sleep(2000);
                Console.WriteLine("..thread1..");
            }));
            tasks.Add(taskFactory.StartNew(() =>
            {
                Thread.Sleep(1800);
                Console.WriteLine("..thread2..");
            }));
            tasks.Add(taskFactory.StartNew(() =>
            {
                Thread.Sleep(1600);
                Console.WriteLine("..thread3..");
            }));
            taskFactory.ContinueWhenAll(tasks.ToArray(), (t) => { Console.WriteLine("all finished......"); });
            Console.WriteLine("end TestTask2........");
        }

运行结果:

start TestTask2........
end TestTask2........
..thread3..
..thread2..
..thread1..
all finished......

 

posted on 2022-04-12 09:26  onlyou13  阅读(81)  评论(0编辑  收藏  举报