Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicitly specifying the TaskScheduler for an implicitly scheduled method

I have the following method which uses implicit scheduling:

private async Task FooAsync()
{
   await Something();
   DoAnotherThing();
   await SomethingElse();
   DoOneLastThing();
}

However, from one particular call-site I want it run on a low-priority scheduler instead of the default:

private async Task BarAsync()
{
   await Task.Factory.StartNew(() => await FooAsync(), 
      ...,
      ...,
      LowPriorityTaskScheduler);
}

How do I achieve this? It seems like a really simple ask, but I'm having a complete mental block!

Note: I'm aware the example won't actually compile :)

like image 866
Lawrence Wagerfield Avatar asked Jan 27 '12 18:01

Lawrence Wagerfield


People also ask

What is Task Scheduler in Java?

Task scheduler interface that abstracts the scheduling of Runnables based on different kinds of triggers. This interface is separate from SchedulingTaskExecutor since it usually represents for a different kind of backend, i.e. a thread pool with different characteristics and capabilities.

How do I use Task Scheduler in spring?

4.1. Let's schedule a task to run at a fixed rate of milliseconds: taskScheduler. scheduleAtFixedRate( new RunnableTask("Fixed Rate of 2 seconds") , 2000); The next RunnableTask will always run after 2000 milliseconds, regardless of the status of the last execution, which may still be running.


1 Answers

Create your own TaskFactory instance, initialized with the scheduler you want. Then call StartNew on that instance:

TaskScheduler taskScheduler = new LowPriorityTaskScheduler();
TaskFactory taskFactory = new TaskFactory(taskScheduler);
...
await taskFactory.StartNew(FooAsync);
like image 69
Stephen Cleary Avatar answered Nov 15 '22 03:11

Stephen Cleary