Search code examples
c#wpfasynchronousasync-awaittaskfactory

Make the TaskScheduler synchronously and run in the main thread


I'm looking for a way to create a TaskScheduler that runs synchronously in the main thread to allow WPF applications to be configured as single thread for debugging purpose.

Any idea?

For now I'm using the sample LimitedTaskScheduler on MSDN that allow to specify the concurrency level (how many threads use) and this extension to set the static TaskFactory before the application starts:

void SetOnTaskFactory(TaskFactory taskFactory)
{
    const BindingFlag = BindingFlags.Static | BindingFlags.NonPublic
    var field = typeof(Task).GetField("s_factory", BindingFlag);
    field.SetValue(null, taskFactory);
}

Solution

  • For testing purposes you can use the CurrentThreadTaskScheduler from ParallelExtensionsExtras library. Basically it's a simple TaskScheduler that executes all tasks on the current thread.