多线程2——Task

1.创建和启动Task任务

 Task task1 = new Task(() => { Console.WriteLine("通过Start启动Task任务"); });
    task1.Start();

    Task.Run(() => { Console.WriteLine("通过Run启动Task任务"); });

    TaskFactory taskFactory = new TaskFactory();
    taskFactory.StartNew(() => { Console.WriteLine("通过工厂代理启动任务"); });

2.多个任务

 List<Task> tasks = new List<Task>();
    for (int i = 0; i < 100; i++)
    {
        int j = i;
        tasks.Add(Task.Run(() =>
        {
            Thread.Sleep(1000);
            Console.WriteLine($"{j}");
        }));
    }
    Task.WaitAny(tasks.ToArray());
    Console.WriteLine("只用等待一个");
    Task.WaitAll(tasks.ToArray());
    Console.WriteLine("等待全部完成");

3.多任务不卡界面等待

 TaskFactory taskFactory2 = new TaskFactory();
    List<Task> tasks2 = new List<Task>();
    for (int i = 0; i < 100; i++)
    {
        int j = i;
        tasks2.Add(taskFactory2.StartNew(() =>
        {
            Thread.Sleep(1000);
            Console.WriteLine($"{j}");
        },TaskCreationOptions.LongRunning));
    }
    taskFactory2.ContinueWhenAll(tasks2.ToArray(), (ss) => { Console.WriteLine($"最后{ss.Length}"); });

4. TaskCreationOptions类

 ①.AttachedToParent:指定将任务附加到任务层次结构中的某个父级,父任务必须等待所有子任务执行完毕才能执行   

  ②. DenyChildAttach: 不允许子任务附加到父任务上

  ③. HideScheduler: 子任务不使用父类Task的Scheduler,而是使用默认的 

  ④. LongRunning:当已知是长时间运行的任务,可以使用该选项

  ⑤. PreferFairness:类似于队列的感觉,尽可能公平的方式安排任务 

5.多任务控制线程数量

 TaskFactory taskFactory3 = new TaskFactory();
    List<Task> tasks3 = new List<Task>();
    for (int i = 0; i < 100; i++)
    {
        int j = i;
        if (tasks3.Where(s => s.Status != TaskStatus.RanToCompletion).ToList().Count > 9)
        {
            Thread.Sleep(500);
            Task.WaitAny(tasks3.ToArray());
            tasks3 = tasks3.Where(s => s.Status != TaskStatus.RanToCompletion).ToList();
        }
        tasks3.Add(taskFactory3.StartNew(() => { Console.WriteLine($"{tasks3.Count}"); }));
    }

 

posted @ 2022-05-16 22:34  乌柒柒  阅读(77)  评论(0编辑  收藏  举报