TPL Queue Processing(TPL 队列处理)
问题描述
我目前正在做一个项目,我需要排队处理一些工作,这是要求:
I'm currently working on a a project and I have a need to queue some jobs for processing, here's the requirement:
- 必须一次处理一个作业
- 必须能够等待排队的项目
所以我想要类似的东西:
So I want something akin to:
Task<result> QueueJob(params here)
{
/// Queue the job and somehow return a waitable task that will wait until the queued job has been executed and return the result.
}
我尝试过一个后台运行任务,它只是将项目从队列中拉出并处理作业,但困难在于从后台任务到方法.
I've tried having a background running task that just pulls items off a queue and processes the job, but the difficulty is getting from a background task to the method.
如果需要,我可以只在 QueueJob 方法中请求完成回调,但如果我能得到一个透明的任务返回,让您等待作业被处理(即使队列中还有工作).
If need be I could go the route of just requesting a completion callback in the QueueJob method, but it'd be great if I could get a transparent Task back that allows you to wait on the job to be processed (even if there are jobs before it in the queue).
推荐答案
Func<T>
不带参数,返回一个T类型的值.作业一个一个运行,你可以等待在返回的任务上获取结果.
Func<T>
takes no parameters and returns a value of type T. The jobs are run one by one and you can wait on the returned task to get the result.
public class TaskQueue
{
private Queue<Task> InnerTaskQueue;
private bool IsJobRunning;
public void Start()
{
Task.Factory.StartNew(() =>
{
while (true)
{
if (InnerTaskQueue.Count > 0 && !IsJobRunning)
{
var task = InnerTaskQueue.Dequeue()
task.Start();
IsJobRunning = true;
task.ContinueWith(t => IsJobRunning = false);
}
else
{
Thread.Sleep(1000);
}
}
}
}
public Task<T> QueueJob(Func<T> job)
{
var task = new Task<T>(() => job());
InnerTaskQueue.Enqueue(task);
return task;
}
}
这篇关于TPL 队列处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:TPL 队列处理
基础教程推荐
- c# Math.Sqrt 实现 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 XML 转换为通用列表 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01