Files
Mapo-IOB-WIN/IOB-UT-NEXT/SingleThreadTaskScheduler.cs
T

50 lines
1.3 KiB
C#

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<Task> _tasks = new BlockingCollection<Task>();
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<Task> GetScheduledTasks()
{
return _tasks.ToArray();
}
public override int MaximumConcurrencyLevel => 1;
public void Dispose()
{
_tasks.CompleteAdding();
}
}