C# - 简单介绍TaskScheduler

6 篇文章 0 订阅

标题: C# - 简单介绍TaskScheduler
Title: C# - A Brief bump to the 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.

    /// <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

使用 TaskScheduler.dll 可以很方便地创建、修改和删除 Windows 任务计划。以下是一个简单C# 示例,演示如何使用 TaskScheduler.dll 创建一个每天执行一次的任务计划: ```csharp using System; using System.IO; using Microsoft.Win32.TaskScheduler; class Program { static void Main(string[] args) { // 创建一个新的计划任务对象 using (TaskService taskService = new TaskService()) { TaskDefinition taskDefinition = taskService.NewTask(); // 设置任务基本属性 taskDefinition.RegistrationInfo.Description = "My Daily Task"; taskDefinition.Principal.LogonType = TaskLogonType.InteractiveToken; taskDefinition.Settings.Enabled = true; // 创建触发器,每天执行一次 DailyTrigger dailyTrigger = new DailyTrigger(); dailyTrigger.Repetition.Interval = TimeSpan.FromDays(1); dailyTrigger.StartBoundary = DateTime.Today.AddHours(9); // 每天 9 点执行 taskDefinition.Triggers.Add(dailyTrigger); // 创建操作,将本地文件复制到远程位置 string sourceFile = @"C:\temp\test.txt"; string destinationPath = @"\\remote\share\test.txt"; CopyAction copyAction = new CopyAction(sourceFile, destinationPath, true); taskDefinition.Actions.Add(copyAction); // 注册任务计划 taskService.RootFolder.RegisterTaskDefinition("My Daily Task", taskDefinition); } } } ``` 在上面的示例中,我们创建了一个名为“My Daily Task”的任务计划,每天 9 点执行。操作是将本地文件复制到远程位置。你可以根据自己的需求修改代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值