C#中Task任务调度机制以及如何自定义
一、TaskScheduler 是什么?
将Task调度给什么地方去执行
TaskScheduler 决定了task如何被调度
Task --》m_invoke()
二、BCL 中现存的Scheduler
2.1 ThreadPoolTaskScheduler
如果没有特别指定,默认就是ThreadPoolTaskScheduler
2.2 SynchronizationContextTaskScheduler
适用于GUI程序、消息循环【Queue】
耗时操作不会放在UI线程去处理
三、实现自己的TaskScheduler
public class Program { static void Main(string[] args) { var scheduler = new CustomerTaskScheduler(); for (int i = 0; i < 100; i++) { Task.Factory.StartNew(() => { Console.WriteLine($"当前线程ID为:{Environment.CurrentManagedThreadId},当前时间{DateTime.Now}"); }, CancellationToken.None, TaskCreationOptions.None, scheduler); } Console.ReadLine(); } } public class CustomerTaskScheduler : TaskScheduler { Thread thread; BlockingCollection<Task> collections = new BlockingCollection<Task>(); public CustomerTaskScheduler() { thread = new Thread(() => { foreach (var task in collections.GetConsumingEnumerable()) { TryExecuteTask(task); } }); thread.Start(); } protected override IEnumerable<Task> GetScheduledTasks() { return collections.ToArray(); } protected override void QueueTask(Task task) { collections.Add(task); } protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { throw new NotImplementedException(); } }