Tag: 同步上下文

为什么TaskScheduler.Current是默认的TaskScheduler?

任务并行库很棒,在过去的几个月里我用了很多。 但是,有一件事真的让我感到困扰: TaskScheduler.Current是默认的任务调度器,而不是TaskScheduler.Default 。 乍一看,这在文档和样本中是绝对不明显的。 Current可能导致微妙的错误,因为它的行为正在改变,取决于你是否在另一个任务。 哪个不容易确定。 假设我正在写一个asynchronous方法库,使用基于事件的标准asynchronous模式来标记原始同步上下文的完成情况,与XxxAsync方法在.NET Framework(例如DownloadFileAsync )中完全相同。 我决定使用任务并行库进行实现,因为使用以下代码很容易实现此行为: public class MyLibrary { public event EventHandler SomeOperationCompleted; private void OnSomeOperationCompleted() { var handler = SomeOperationCompleted; if (handler != null) handler(this, EventArgs.Empty); } public void DoSomeOperationAsync() { Task.Factory .StartNew ( () => Thread.Sleep(1000) // simulate a long operation , CancellationToken.None , TaskCreationOptions.None , TaskScheduler.Default […]