C#线程池并不直接支持任务的优先级调度,但可以通过自定义任务调度器来实现任务的优先级调度。
以下是一种简单的实现方式:
public class CustomTask
{
public int Priority { get; set; }
public Action TaskAction { get; set; }
public CustomTask(int priority, Action taskAction)
{
Priority = priority;
TaskAction = taskAction;
}
}
public class CustomTaskScheduler
{
private List<CustomTask> tasks = new List<CustomTask>();
public void EnqueueTask(CustomTask task)
{
tasks.Add(task);
tasks = tasks.OrderBy(t => t.Priority).ToList();
}
public void Start()
{
foreach (CustomTask task in tasks)
{
ThreadPool.QueueUserWorkItem(state => task.TaskAction());
}
}
}
CustomTaskScheduler taskScheduler = new CustomTaskScheduler();
// 添加任务
taskScheduler.EnqueueTask(new CustomTask(1, () => Console.WriteLine("Task 1")));
taskScheduler.EnqueueTask(new CustomTask(2, () => Console.WriteLine("Task 2")));
taskScheduler.EnqueueTask(new CustomTask(3, () => Console.WriteLine("Task 3")));
// 启动调度
taskScheduler.Start();
这样就可以根据任务的优先级来调度任务的执行顺序。当添加任务时,按照任务的优先级进行排序,然后依次执行。