Question

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);
}
Was it helpful?

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.

OTHER TIPS

If you want to create a SynchronousTaskScheduler, you can do so using below code.

void Main()
{
    SynchronousTaskScheduler taskScheduler = new SynchronousTaskScheduler();
    for (int i = 0; i < 100; i++)
    {
        Task.Factory.StartNew(() => SomeMethod(i), CancellationToken.None, TaskCreationOptions.None, taskScheduler);
    }
}

void SomeMethod(int number)
{
    $"Scheduled task {number}".Dump();
}

// Define other methods and classes here
class SynchronousTaskScheduler : TaskScheduler
{
    public override int MaximumConcurrencyLevel
    {
        get { return 1; }
    }

    protected override void QueueTask(Task task)
    {
        TryExecuteTask(task);
    }

    protected override bool TryExecuteTaskInline(
        Task task,
        bool taskWasPreviouslyQueued)
    {
        return TryExecuteTask(task);
    }

    protected override IEnumerable<Task> GetScheduledTasks()
    {
        return Enumerable.Empty<Task>();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top