C# - 简单介绍TaskScheduler task Scheduler根据定义
The task Scheduler by the definition blurb.
“Is the class where the usage context is within the task libraries. “
它的作用像是WPF/Winform时代的SynchronizationContext.
It is like the Synchronization context in the cross WPF/Win forms era.
像SynchronizationContext.一样,TaskScheduler也有可能依赖特定的UI SynchronizationContext.
As with the Synchronization context, we may have requirement for like the UI context synchronization.
代码如下:
Give the code as below.
C#代码///<summary> ///ThisserviceisdesignedtoreturnaTaskSchedulerforapplication 'smain,UIthread. ///ThisserviceMUSTbeinstantiatedonUIthread. ///</summary> [DebuggerNonUserCode] publicclassUITaskSchedulerService:IUITaskSchedulerService { PR ivatestaticreadonlyUITaskSchedulerServiceInstanceField=newUITaskSchedulerService();privatestaticreadonlyTaskSchedulerTaskSchedulerUI; privatestaticreadonlyThreadGuiThread; staticUITaskSchedulerService() { GuiThread=Thread.CurrentThread; TaskSchedulerUI=TaskScheduler.FromCurrentSynchronizationContext(); } ///<summary> ///Getstheinstance. ///</summary> publicstaticUITaskSchedulerServiceInstance { get { returnInstanceField; } } ///<summary> ///GetTaskSchedulertoscheduleTasksonUIthread. ///</summary> ///<returns>TaskSchedulertoscheduleTasksonUIthread.</returns> publicTaskSchedulerGetUITaskScheduler() { returnTaskSchedulerUI; } ///<summary> ///CheckwhethercurrenttreadisUItread ///</summary> ///<returns><c>true</c>ifcurrenttreadisUItread.</returns> publicboolIsOnUIThread() { returnGuiThread==Thread.CurrentThread; } }
该class的要求是必须在UI thread初始化。
The requirement for the UITaskShcedulerService is that you should construct the singleton instance to start from a UI threads.
因为他内部使用的是TaskScheduler.FromCurrentSynchronizationContext,根据MSDN的TaskScheduler Class定义,它拿到的是当前thread的synchronization context
Because it internally use theTaskScheduler.FromCurrentSynchronizationContext. and from theTaskScheduler Classfrom MSDN, it retrieve the current thread’s synchronization context.
C#代码Task.Factory .StartNew( ()=> _riskProvider.GetRiskPnL(), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default) .ContinueWith( (task)=>ProcessResults(task.Result), UITaskSchedulerService.Instance.GetUITaskScheduler(