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();
        }

    }

 

posted @ 2020-02-02 21:10  王大师123  阅读(1012)  评论(0编辑  收藏  举报