简体   繁体   中英

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

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

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>();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM