Search code examples
c#.nettask-parallel-libraryasync-ctp

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


Solution

  • 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);