using System; using System.Collections.Generic; using System.Collections.Concurrent; using System.Threading; using System.Threading.Tasks; public class SingleThreadTaskScheduler : TaskScheduler, IDisposable { private readonly BlockingCollection _tasks = new BlockingCollection(); private readonly Thread _thread; public SingleThreadTaskScheduler() { _thread = new Thread(() => { foreach (var task in _tasks.GetConsumingEnumerable()) { // Esegue il task sul thread dedicato base.TryExecuteTask(task); } }); _thread.IsBackground = true; _thread.Name = "SingleWorkerThread"; _thread.Start(); } protected override void QueueTask(Task task) { _tasks.Add(task); } protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { // Consente l'esecuzione inline solo se siamo già sul thread dedicato return Thread.CurrentThread == _thread && base.TryExecuteTask(task); } protected override IEnumerable GetScheduledTasks() { return _tasks.ToArray(); } public override int MaximumConcurrencyLevel => 1; public void Dispose() { _tasks.CompleteAdding(); } }