TPL队列处理 [英] TPL Queue Processing
问题描述
我目前正在对AA的项目,我有一个需要排队等候处理一些工作,这里的要求:
I'm currently working on a a project and I have a need to queue some jobs for processing, here's the requirement:
- 工作必须在同一时间内处理的有一个
- 排队的项目必须能够被上
所以我想一个类似于:
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队列处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!