简体   繁体   English

如何从自定义TaskScheduler回退到Default TaskScheduler

[英]How do I fallback to the Default TaskScheduler from a custom TaskScheduler

Let's say I want to create a custom TaskScheduler, but inside it, fall back to the default if some criteria do not apply. 假设我想创建一个自定义TaskScheduler,但在其中,如果某些条件不适用,则回退到默认值。 How do I do that? 我怎么做?

Eg 例如

protected override void QueueTask(Task task) {
   if (/* some condition */) {
       /* schedule task manually, does not matter */
   }

   /* queue task on default -- how? */
}

protected override IEnumerable<Task> GetScheduledTasks() {
    return Enumerable.Concat(/* my tasks */, /* tasks from default -- how? */);
}

I don't think you can (or should) do this, even if you resorted to reflection hacks. 我不认为你可以(或应该)这样做,即使你使用反射黑客。 In theory, you'd need to derive your custom TaskScheduler from existing non-abstract task scheduler, eg ThreadPoolTaskScheduler . 理论上,您需要从现有的非抽象任务调度程序派生自定义TaskScheduler ,例如ThreadPoolTaskScheduler

However, you can't because all non-abstract implementations of TaskScheduler in TPL are either private or internal . 但是,你不能,因为TPL中TaskScheduler 所有非抽象实现都是privateinternal

In case with TaskScheduler.QueueTask , it might be tempting to simply forward the call to Task.Start : 对于TaskScheduler.QueueTask ,可能很容易将调用转发到Task.Start

protected override void QueueTask(Task task) {
   if (/* some condition */) {
       /* schedule task manually, does not matter */
   }

   /* queue task on default -- how? */
   task.Start(TaskScheduler.Default);
}

However, you can not do this, either. 但是,你也不能这样做。 The implementation of Task.Start calls TaskScheduler.QueueTask internally, which would result in infinite recursion. Task.Start实现在Task.Start调用TaskScheduler.QueueTask ,这将导致无限递归。

Moreover, the Task object stores a reference to the task scheduler inside Task.Start . 此外, Task对象在Task.Start存储对任务调度程序的Task.Start So, say, if you used reflection to call ThreadPoolTaskScheduler.QueueTask , it would break the connection between the task and its task scheduler. 因此,如果您使用反射来调用ThreadPoolTaskScheduler.QueueTask ,它将破坏任务与其任务调度程序之间的连接。

So, there's a good reason that QueueTask , GetScheduledTasks and some other methods of TaskScheduler are declared as protected . 因此,有一个很好的理由将QueueTaskGetScheduledTasksTaskScheduler其他一些方法声明为protected If you're into implementing a custom task scheduler, you have to provide the full implementation. 如果您要实现自定义任务计划程序,则必须提供完整的实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM