在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启动任务。