在C#中,可以使用Task類和TaskScheduler類來實現單線程的任務調度
下面是一個簡單的示例:
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
class SingleThreadTaskScheduler : TaskScheduler
{
private readonly LinkedList<Task> _tasks = new LinkedList<Task>();
private readonly Thread _thread;
public SingleThreadTaskScheduler()
{
_thread = new Thread(ProcessTasks);
_thread.Start();
}
protected override void QueueTask(Task task)
{
lock (_tasks)
{
_tasks.AddLast(task);
}
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
return false;
}
protected override IEnumerable<Task> GetScheduledTasks()
{
lock (_tasks)
{
return _tasks.ToArray();
}
}
private void ProcessTasks()
{
while (true)
{
Task task;
lock (_tasks)
{
if (_tasks.Count == 0)
{
break;
}
task = _tasks.First.Value;
_tasks.RemoveFirst();
}
TryExecuteTask(task);
}
}
}
class Program
{
static async Task Main(string[] args)
{
var scheduler = new SingleThreadTaskScheduler();
var factory = new TaskFactory(scheduler);
for (int i = 0; i < 5; i++)
{
int index = i;
var task = factory.StartNew(() =>
{
Console.WriteLine($"Task {index} is running on thread {Thread.CurrentThread.ManagedThreadId}");
Thread.Sleep(1000);
});
}
await Task.Delay(2000);
Console.WriteLine("Main thread is exiting...");
}
}
在這個示例中,我們創建了一個SingleThreadTaskScheduler類,該類繼承自TaskScheduler。我們重寫了QueueTask、TryExecuteTaskInline和GetScheduledTasks方法,以實現單線程的任務調度。然后,我們使用TaskFactory和自定義的TaskScheduler創建任務,并將任務添加到調度隊列中。最后,我們使用Task.Run或Task.StartNew啟動任務。