[英]How to delay 'hot' tasks so they can processed in a set order
Say I have a set of tasks: 说我有一组任务:
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: 问题约束/细节是:
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. 主要问题是,只要我调用相关方法(如DoThis()...)以返回每个任务,该任务就已经“热”或正在运行,违反了上面的(2)。
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. 我曾尝试使用.ContinueWith(..),但是如果我像上面那样调用每个任务来设置延续,或将它们添加到列表或集合中,它们就已经开始了。
Not sure if Lazy < T > might help but can't see how at present? 不知道Lazy <T>是否有帮助,但目前看不到吗?
Hope this makes sense as I'm fairly new to async / await / tasks. 希望这是有道理的,因为我对异步/等待/任务还很陌生。
Many thanks in advance. 提前谢谢了。
Calling a method runs code. 调用方法将运行代码。 If you want an object that will call this method later , then use a delegate.
如果要使用稍后将调用此方法的对象,请使用委托。
In this case, you could use Func<Task>
, which is an asynchronous delegate. 在这种情况下,可以使用
Func<Task>
,它是一个异步委托。 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();
you can simply create tasks with its constructor and then, call execution with .Start() methods. 您可以简单地使用其构造函数创建任务,然后使用.Start()方法调用执行。
Here an example: 这里是一个例子:
var taskList = InitQueue();
foreach (var t in taskList.OrderBy(i => i.Order))
{
//Here I can skedule an existing task
t.TaskToRun.Start();
t.TaskToRun.Wait();
Console.WriteLine($"Task {t.Order} has finished its job");
}
public class TaskQueue : List<TaskItem>
{
}
public class TaskItem
{
public int Order { get; set; }
public Task TaskToRun { get; set; }
}
private static TaskQueue InitQueue()
{
var queue = new TaskQueue();
queue.Add(new TaskItem
{
Order = 1,
TaskToRun = new Task(() =>
{
Task.Delay(500);
Console.WriteLine("Hello from task 1");
})
});
queue.Add(new TaskItem
{
Order = 4,
TaskToRun = new Task(() => Console.WriteLine("Hello from task 4"))
});
queue.Add(new TaskItem
{
Order = 3,
TaskToRun = new Task(() =>
{
Task.Delay(5000);
Console.WriteLine("Hello from task 3");
})
});
queue.Add(new TaskItem
{
Order = 2,
TaskToRun = new Task(() => Console.WriteLine("Hello from task 2"))
});
return queue;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.