Task和TaskFactory


    /// 1 Task:Waitall  WaitAny  Delay
    /// 2 TaskFactory:ContinueWhenAny ContinueWhenAll
    class Program
    {
        //Task.WaitAny  WaitAll都是阻塞當前線程,等任務完成后執行操作
        //Delay 異步等待
        //ContinueWhenAny  ContinueWhenAll 非阻塞式的回調;而且使用的線程可能是新線程,也可能是剛完成任務的線程,唯一不可能是主線程
        static void Main(string[] args)
        {
            {
                Task task = new Task(() => { Console.WriteLine("開始線程1"); });
                task.Start();
                task.ContinueWith(t =>
                {
                    Console.WriteLine($"線程完成,{Thread.CurrentThread.ManagedThreadId.ToString("00")}");
                }); //回調
            }
            {
                Task<int> task = Task.Run(() =>
                {
                    Console.WriteLine("開始線程2");
                    return DateTime.Now.Year;
                });
                Console.WriteLine(task.Result);//獲取返回值,會阻塞
            }
          
            {
                TaskFactory taskFactory = Task.Factory;
                Task task = taskFactory.StartNew(() => Console.WriteLine("開始線程3"));
            }
            //{
            //    ThreadPool.SetMaxThreads(8, 8);
            //    //線程池是單例的,全局唯一的
            //    //設置后,同時並發的Task只有8個;而且線程是復用的;
            //    //Task的線程是源於線程池
            //    //全局的,請不要這樣設置!!!
            //    for (int i = 0; i < 100; i++)
            //    {
            //        int k = i;
            //        Task.Run(() =>
            //        {
            //            Console.WriteLine($"This is {k} running ThreadId={Thread.CurrentThread.ManagedThreadId.ToString("00")}");
            //            Thread.Sleep(2000);
            //        });
            //    }
            //}
            //{
            //    {
            //        Stopwatch stopwatch = new Stopwatch();
            //        stopwatch.Start();
            //        Console.WriteLine("在Sleep之前");
            //        Thread.Sleep(2000);//同步等待--當前線程等待2s 然后繼續
            //        Console.WriteLine("在Sleep之后");
            //        stopwatch.Stop();
            //        Console.WriteLine($"Sleep耗時{stopwatch.ElapsedMilliseconds}");
            //    }
            //    {
            //        Stopwatch stopwatch = new Stopwatch();
            //        stopwatch.Start();
            //        Console.WriteLine("在Delay之前");
            //        Task task = Task.Delay(2000)
            //            .ContinueWith(t =>
            //            {
            //                stopwatch.Stop();
            //                Console.WriteLine($"Delay耗時{stopwatch.ElapsedMilliseconds}");

            //                Console.WriteLine($"This is ThreadId={Thread.CurrentThread.ManagedThreadId.ToString("00")}");
            //            });//異步等待--等待2s后啟動新任務
            //        Console.WriteLine("在Delay之后");
            //        //stopwatch.Stop();
            //        //Console.WriteLine($"Delay耗時{stopwatch.ElapsedMilliseconds}");
            //    }
            //}
            //{
            //    //開發可以多人合作---多線程--提升性能
            //    TaskFactory taskFactory = new TaskFactory();
            //    List<Task> taskList = new List<Task>();
            //    taskList.Add(Task.Run(() => Coding("張三", "Portal")));
            //    taskList.Add(taskFactory.StartNew(() => Coding("李四", "  DBA ")));
            //    taskList.Add(taskFactory.StartNew(() => Coding("王五", "Client")));
            //    taskList.Add(taskFactory.StartNew(() => Coding("趙六", "BackService")));
            //    taskList.Add(taskFactory.StartNew(() => Coding("田七", "Wechat")));

            //    taskFactory.ContinueWhenAny(taskList.ToArray(), array =>
            //    {
            //        Console.WriteLine($"開發完成 准備測試,{ Thread.CurrentThread.ManagedThreadId.ToString("00")}");
            //    });
            //    taskFactory.ContinueWhenAll(taskList.ToArray(), array =>
            //    {
            //        Console.WriteLine($"項目全部開發完成准備測試,{Thread.CurrentThread.ManagedThreadId.ToString("00")}");
            //    });
            //    ////ContinueWhenAny  ContinueWhenAll 非阻塞式的回調;而且使用的線程可能是新線程,也可能是剛完成任務的線程,唯一不可能是主線程

            //    ////阻塞當前線程,等着任意一個任務完成
            //    Task.WaitAny(taskList.ToArray());

            //    //Task.WaitAny(taskList.ToArray(), 1000);//也可以限時等待
            //    Console.WriteLine($"有人員完成開發,准備部署環境,{ Thread.CurrentThread.ManagedThreadId.ToString("00")}");
            //    //需要能夠等待全部線程完成任務再繼續  阻塞當前線程,等着全部任務完成
            //    Task.WaitAll(taskList.ToArray());
            //    Console.WriteLine($"項目開發完成,{ Thread.CurrentThread.ManagedThreadId.ToString("00")}");
            //    ////Task.WaitAny  WaitAll都是阻塞當前線程,等任務完成后執行操作
            //    ///阻塞卡界面,是為了並發以及順序控制
            //}

            //{
            //    TaskFactory taskFactory = new TaskFactory();
            //    List<Task> taskList = new List<Task>();
            //    taskList.Add(Task.Run(() => Coding("張三", "Portal")));
            //    taskList.Add(taskFactory.StartNew((o) => Coding("李四", "  DBA "),"李四"));
            //    taskList.Add(taskFactory.StartNew((o) => Coding("王五", "Client"), "王五"));
            //    taskList.Add(taskFactory.StartNew((o) => Coding("趙六", "BackService"), "趙六"));
            //    taskList.Add(taskFactory.StartNew((o) => Coding("田七", "Wechat"), "田七"));

            //     //輸出誰先完成
            //    taskFactory.ContinueWhenAny(taskList.ToArray(), array =>
            //    {
            //        Console.WriteLine($"{array.AsyncState},開發完成 准備測試,{ Thread.CurrentThread.ManagedThreadId.ToString("00")}");
            //    });
            //    taskFactory.ContinueWhenAll(taskList.ToArray(), array =>
            //    {
            //        Console.WriteLine($"項目全部開發完成准備測試,{Thread.CurrentThread.ManagedThreadId.ToString("00")}");
            //    });
            //}

            //{
            //    List<Task> tasks = new List<Task>();
            //    //控制線程數量為20個
            //    for (int i = 0; i < 10000; i++)
            //    {
            //        int k = i;
            //        if (tasks.Count(t => t.Status != TaskStatus.RanToCompletion) >= 20)
            //        {
            //            Task.WaitAny(tasks.ToArray());
            //            tasks = tasks.Where(t => t.Status != TaskStatus.RanToCompletion).ToList();
            //        }
            //        tasks.Add(Task.Run(() =>
            //        {
            //            Console.WriteLine($"This is {k} running ThreadId={Thread.CurrentThread.ManagedThreadId.ToString("00")}");
            //            Thread.Sleep(2000);
            //        }));
            //    }
            //}

            /// <summary>
            /// 模擬Coding過程
            /// </summary>
            /// <param name="name"></param>
            /// <param name="projectName"></param>
            void Coding(string name, string projectName)
            {
                Console.WriteLine($"****************Coding Start  {name} {projectName}  {Thread.CurrentThread.ManagedThreadId.ToString("00")} {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}***************");
                long lResult = 0;
                for (int i = 0; i < 1_000_000_000; i++)
                {
                    lResult += i;
                }

                Console.WriteLine($"****************Coding   End  {name} {projectName} {Thread.CurrentThread.ManagedThreadId.ToString("00")} {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")} {lResult}***************");
            }

            Console.ReadKey();
        }

    }

 


免責聲明!

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



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