首页 > 学院 > 开发设计 > 正文

C#

2019-11-17 03:07:19
字体:
来源:转载
供稿:网友

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#代码收藏代码
  1. ///<summary>
  2. ///ThisserviceisdesignedtoreturnaTaskSchedulerforapplication'smain,UIthread.
  3. ///ThisserviceMUSTbeinstantiatedonUIthread.
  4. ///</summary>
  5. [DebuggerNonUserCode]
  6. publicclassUITaskSchedulerService:IUITaskSchedulerService
  7. {
  8. PRivatestaticreadonlyUITaskSchedulerServiceInstanceField=newUITaskSchedulerService();
  9. privatestaticreadonlyTaskSchedulerTaskSchedulerUI;
  10. privatestaticreadonlyThreadGuiThread;
  11. staticUITaskSchedulerService()
  12. {
  13. GuiThread=Thread.CurrentThread;
  14. TaskSchedulerUI=TaskScheduler.FromCurrentSynchronizationContext();
  15. }
  16. ///<summary>
  17. ///Getstheinstance.
  18. ///</summary>
  19. publicstaticUITaskSchedulerServiceInstance
  20. {
  21. get
  22. {
  23. returnInstanceField;
  24. }
  25. }
  26. ///<summary>
  27. ///GetTaskSchedulertoscheduleTasksonUIthread.
  28. ///</summary>
  29. ///<returns>TaskSchedulertoscheduleTasksonUIthread.</returns>
  30. publicTaskSchedulerGetUITaskScheduler()
  31. {
  32. returnTaskSchedulerUI;
  33. }
  34. ///<summary>
  35. ///CheckwhethercurrenttreadisUItread
  36. ///</summary>
  37. ///<returns><c>true</c>ifcurrenttreadisUItread.</returns>
  38. publicboolIsOnUIThread()
  39. {
  40. returnGuiThread==Thread.CurrentThread;
  41. }
  42. }

该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#代码收藏代码
  1. Task.Factory
  2. .StartNew(
  3. ()=>
  4. _riskProvider.GetRiskPnL(),
  5. CancellationToken.None,
  6. TaskCreationOptions.None,
  7. TaskScheduler.Default)
  8. .ContinueWith(
  9. (task)=>ProcessResults(task.Result),
  10. UITaskSchedulerService.Instance.GetUITaskScheduler(
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表