等待在内部范围的调度程序上运行后如何强制代码?

时间:2018-10-16 02:44:20

标签: c# async-await

我希望在没有SynchronizationContext的情况下,执行流程不会更改线程。此代码显示执行流会更改运行线程,并且在await的线程中执行ThreadPool之后的代码。

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Test
{
    public class Program
    {
        public static async Task Main()
        {
            var ts = new MyTaskScheduler();
            var t = Task.Factory.StartNew(() => Console.WriteLine($"Inside '{Thread.CurrentThread.Name}'"), CancellationToken.None, TaskCreationOptions.None, ts);
            await t;
            Console.WriteLine($"Outside '{Thread.CurrentThread.Name}'");
            Console.ReadLine();
        }
    }
    public class MyTaskScheduler : TaskScheduler
    {
        private readonly Thread thread;
        private readonly BlockingCollection<Task> queue;

        public MyTaskScheduler()
        {
            queue = new BlockingCollection<Task>();
            thread = new Thread(() => Loop()) { Name = "my thread" };
            thread.Start();
        }

        private void Loop()
        {
            while (true)
                foreach (var task in queue.GetConsumingEnumerable())
                    TryExecuteTask(task);
        }

        protected override void QueueTask(Task task) => queue.Add(task);
        protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) => TryExecuteTask(task);
        protected override IEnumerable<Task> GetScheduledTasks() => queue.ToList();
        public override int MaximumConcurrencyLevel => 1;
    }
}

screenshot

我可以使用TaskCreationOptions.HideScheduler来获得所需的行为。但是从它的描述中,我无法确定这是在这种情况下的推荐设置还是带来未知后果的副作用。

0 个答案:

没有答案