1.目的实现一个有优先级列队处理的线程 2.代码
消费:
public class PriorityQueueTaskService
{
public static PriorityQueue<QueueDto, int> queueList = new();
public static async Task PriorityQueueTask()
{
try
{
_ = Task.Factory.StartNew(async () =>
{
while (true)
{
try
{
while (queueList.TryDequeue(out QueueDto? item, out int priority))
{
if (item == null) continue;
Console.WriteLine($"Popped Item : {item.Name}. Priority Was : {priority}");
}
}
catch(Exception ex)
{
}
await Task.Delay(100);
}
});
}
catch (Exception ex)
{
}
}
}
生产:
PriorityQueueTaskService.queueList.Enqueue(queueDto, priority);
3.这种思路可能解决问题是 一些大量请求过来的数据队列未能及时消费,但是有些相对更为紧急需要处理的队列则可以插队处理。
|