我希望在没有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;
}
}
我可以使用TaskCreationOptions.HideScheduler
来获得所需的行为。但是从它的描述中,我无法确定这是在这种情况下的推荐设置还是带来未知后果的副作用。