Search code examples
c#task-parallel-libraryschedulersynchronizationcontext

How do I start a Task with a specific scheduler (eg GUI)


I am trying to create a Task with the TPL. eg:

Task.Factory.StartNew(() => DoSomething());

This works fine, but now I want to start it on the gui thread.

I can cache the gui scheduler with:

_uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();

but I can't see how to start a new task using this scheduler. All the examples I can find use Task.ContinueWith() to schedule a second task using _uiScheduler once the initial task has finished, but I want to create the initial task using this scheduler.

Cheers


Solution

  • There is a huge number of overloads of StartNew. One of them accepts a scheduler. Simply pass None for the other parameters:

    Task.Factory.StartNew(() => DoSomething(), CancellationToken.None,
                          TaskCreationOptions.None, _uiScheduler);