TaskScheduler
两种TaskScheduler
- ThreadPoolTaskScheduler(默认,线程池调度形式)
- SychronizationTaskScheduler
Task t = new Task(() => { try { //耗时操作 Thread.Sleep(4000); this.label1.Text = "hello"; } catch (Exception ex) { throw; } }); t.Start(TaskScheduler.FromCurrentSynchronizationContext());
以上方法会阻塞主线程,造成主界面卡顿,改进后如下:
耗时操作放在线程池中,更新结果放在同步上下文中
private void button1_Click(object sender, EventArgs e) { Task t = Task.Run(() => { try { //耗时操作 Thread.Sleep(4000); } catch (Exception ex) { throw; } }).ContinueWith(ta => { //更新操作 this.label1.Text = "hello"; }, TaskScheduler.FromCurrentSynchronizationContext()); }
自定义scheduler
public class PerThreadScheduler : TaskScheduler { protected override IEnumerable<Task> GetScheduledTasks() { throw new NotImplementedException(); } protected override void QueueTask(Task task) { Thread t = new Thread(() => { TryExecuteTask(task); }); t.Start(); } protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { throw new NotImplementedException(); } }
Task 、TaskScheduler 、Thread 、ThreadPoll关系图