使用 Task.ContinueWith 创建执行队列? [英] Creating a execution queue by using Task.ContinueWith?

查看:26
本文介绍了使用 Task.ContinueWith 创建执行队列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在后台执行多个操作,但它们必须一个接一个同步执行.

I have several actions that I want to execute in the background, but they have to be executed synchronously one after the other.

我想知道使用 Task.ContinueWith 方法来实现这一点是否是个好主意.你预见到这有什么问题吗?

I was wondering if it's a good idea to use the Task.ContinueWith method to achieve this. Do you foresee any problems with this?

我的代码如下所示:

private object syncRoot =new object();
private Task latestTask;

public void EnqueueAction(System.Action action)
{
    lock (syncRoot)
    {
        if (latestTask == null)
            latestTask = Task.Factory.StartNew(action);
        else
            latestTask = latestTask.ContinueWith(tsk => action());
    }
}

推荐答案

这应该按设计工作(使用事实,如果相应的任务已经完成,TPL 将立即安排继续).

This should work as designed (using the fact that TPL will schedule the continuation immediately if the corresponding task already has completed).

就个人而言,在这种情况下,我只会使用使用并发队列的专用线程 (ConcurrentQueue) 从中提取任务 - 这更明确但更容易解析阅读代码,特别是如果您想找出当前排队的任务数量等.

Personally in this case I would just use a dedicated thread using a concurrent queue (ConcurrentQueue) to draw tasks from - this is more explicit but easier to parse reading the code, especially if you want to find out i.e. how many tasks are currently queued etc.

这篇关于使用 Task.ContinueWith 创建执行队列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆