문제

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 the CurrentThreadTaskScheduler 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>();
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top