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();
這樣就可以根據任務的優先級來調度任務的執行順序。當添加任務時,按照任務的優先級進行排序,然后依次執行。