Explicitly specifying the TaskScheduler for an implicitly scheduled method

1.1k views Asked by At

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 :)

2

There are 2 answers

3
Stephen Cleary On BEST ANSWER

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);
0
AudioBubble On

You can set thread-priority, but within the thread's method:

System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.BelowNormal;

Check other values of ThreadPriority enum.