Explicitly specifying TaskScheduler for an implicitly scheduled method

I have the following method that uses implicit planning:

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

However, from one specific call site, I want it to run in the low-priority scheduler instead of the standard one:

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

How do I achieve this? This seems like a really simple question, but I have a complete mental block!

Note: I know that the example will not actually compile :)

+5
source share
2 answers

Create your own instance TaskFactory, initialized by the scheduler you want. Then call StartNewin this instance:

TaskScheduler taskScheduler = new LowPriorityTaskScheduler();
TaskFactory taskFactory = new TaskFactory(taskScheduler);
...
await taskFactory.StartNew(FooAsync);
+7
source

, :

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

ThreadPriority enum.

-1

All Articles