TPL 队列处理

TPL Queue Processing(TPL 队列处理)

本文介绍了TPL 队列处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在做一个项目,我需要排队处理一些工作,这是要求:

I'm currently working on a a project and I have a need to queue some jobs for processing, here's the requirement:

  1. 必须一次处理一个作业
  2. 必须能够等待排队的项目

所以我想要类似的东西:

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 队列处理

基础教程推荐