首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

C# - 简略介绍TaskScheduler

2013-07-08 
C# - 简单介绍TaskScheduler/// summary/// This service is designed to return a TaskScheduler for a

C# - 简单介绍TaskScheduler
/// <summary> /// This service is designed to return a TaskScheduler for application's main, UI thread. /// This service MUST be instantiated on UI thread. /// </summary> [DebuggerNonUserCode] public class UITaskSchedulerService : IUITaskSchedulerService { private static readonly UITaskSchedulerService InstanceField = new UITaskSchedulerService(); private static readonly TaskScheduler TaskSchedulerUI; private static readonly Thread GuiThread; static UITaskSchedulerService() { GuiThread = Thread.CurrentThread; TaskSchedulerUI = TaskScheduler.FromCurrentSynchronizationContext(); } /// <summary> /// Gets the instance. /// </summary> public static UITaskSchedulerService Instance { get { return InstanceField; } } /// <summary> /// Get TaskScheduler to schedule Tasks on UI thread. /// </summary> /// <returns>TaskScheduler to schedule Tasks on UI thread.</returns> public TaskScheduler GetUITaskScheduler() { return TaskSchedulerUI; } /// <summary> /// Check whether current tread is UI tread /// </summary> /// <returns><c>true</c>if current tread is UI tread.</returns> public bool IsOnUIThread() { return GuiThread == 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 the?TaskScheduler.FromCurrentSynchronizationContext. and from the?TaskScheduler Class?from MSDN, it retrieve the current thread’s synchronization context.

Task.Factory                .StartNew(                    () =>                    _riskProvider.GetRiskPnL(),                    CancellationToken.None,                    TaskCreationOptions.None,                    TaskScheduler.Default)                  .ContinueWith(                    (task) => ProcessResults(task.Result),                    UITaskSchedulerService.Instance.GetUITaskScheduler()                    )                //.ContinueWith(                // (task) => ProcessResults(task.Result),                // TaskScheduler.FromCurrentSynchronizationContext())                .LogTaskExceptionIfAny(Log)                .ContinueWith(x => DataUpdater());

?处理结果需要dispatch到UI thread上,这样才能正确的显示。

?

We need to dispatch the process result back to the UI thread so that display can be properly handled.


References:

TaskScheduler Class

热点排行