简体   繁体   English

使TaskScheduler同步并在主线程中运行

[英]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.我正在寻找一种方法来创建在主线程中同步运行的 TaskScheduler,以允许将 WPF 应用程序配置为单线程以进行调试。

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:现在我正在使用 MSDN 上的示例LimitedTaskScheduler ,它允许指定并发级别(使用多少线程)和这个扩展来在应用程序启动之前设置静态 TaskFactory:

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.出于测试目的,您可以使用 ParallelExtensionsExtras 库中的CurrentThreadTaskScheduler Basically it's a simple TaskScheduler that executes all tasks on the current thread.基本上它是一个简单的TaskScheduler ,它在当前线程上执行所有任务。

If you want to create a SynchronousTaskScheduler, you can do so using below code.如果要创建 SynchronousTaskScheduler,可以使用以下代码。

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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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