TPL队列处理

编程入门 行业动态 更新时间:2024-10-10 10:27:39
本文介绍了TPL队列处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我目前正在对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队列处理

    本文发布于:2023-11-28 20:36:41,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1643872.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:队列   TPL

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!