TPL 队列处理

编程入门 行业动态 更新时间:2024-10-10 08:25:13
本文介绍了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 队列处理

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

    发布评论

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

    >www.elefans.com

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