如何延迟“热"任务以使它们能够按固定顺序进行处理 [英] How to delay 'hot' tasks so they can processed in a set order

查看:53
本文介绍了如何延迟“热"任务以使它们能够按固定顺序进行处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一系列任务:

        var task1 = DoThisAsync(...);
        var task2 = DoThatAsync(...);
        var task3 = DoOtherAsync(...);
        var taskN...

我正在寻找一种顺序处理一组任务的方法(由包含集合中的位置确定),但是要让任务仅在轮到他们时才运行/开始,而不是在之前-并把所有这些都包装好完成自己的任务.

I am looking for a way to process a set of tasks in order (determined by place in containing collection say), but to have the tasks only run/start when its their turn and not before - and have all of that wrapped up in its own task.

问题约束/详细信息是:

Problem constraints / details are:

  1. 这些任务需要按照一定的顺序执行,即task1,task2,...
  2. 上一个任务必须异步完成,下一个任务才能开始
  3. 任务数是可变的
  4. 每次运行代码时,可能会指定一组不同的任务
  5. 任务的顺序和数量是预先知道的.

主要问题是,只要我调用相关方法(如DoThis()...)以返回每个任务,该任务就已经热"或正在运行,违反了上面的(2).

The main problem is that as soon as I call the relevant method (like DoThis()...) to return each task, that task is already 'hot' or running, violating (2) above.

我曾经尝试过使用.ContinueWith(..),但是如果我像上面那样调用每个任务来设置延续,或者将它们添加到列表或集合中,它们就已经开始了.

I have tried working with.ContinueWith(..) , but if I call each of tasks like above to set the continuations or add them to a list or collection they've already started.

不确定是否懒惰< T>可能有帮助,但目前看不到吗?

Not sure if Lazy < T > might help but can't see how at present?

希望这很有意义,因为我对异步/等待/任务还很陌生.

Hope this makes sense as I'm fairly new to async / await / tasks.

非常感谢.

推荐答案

调用方法将运行代码.如果您想要一个对象,该对象将调用此方法以后,请使用委托.

Calling a method runs code. If you want an object that will call this method later, then use a delegate.

在这种情况下,您可以使用Func<Task>,这是一个异步委托.这些列表就足够了:

In this case, you could use Func<Task>, which is an asynchronous delegate. A list of these should suffice:

// Build the list of operations in order.
var operations = new List<Func<Task>>();
operations.Add(() => DoThisAsync(...));
operations.Add(() => DoThatAsync(...));
operations.Add(() => DoOtherAsync(...));

// Execute them all one at a time.
foreach (var operation in operations)
  await operation();

这篇关于如何延迟“热"任务以使它们能够按固定顺序进行处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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