简体   繁体   English

如何延迟“热”任务以使它们能够按固定顺序进行处理

[英]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: 问题约束/细节是:

  1. These tasks need to be performed in a certain order ietask1, task2,... 这些任务需要按照一定的顺序执行,即task1,task2,...
  2. The previous task must complete asynchronously before the next can start 上一个任务必须异步完成才能下一个任务开始
  3. The number of tasks is variable 任务数是可变的
  4. A different set of tasks may be nominated each time code is run 每次运行代码时,可能会指定一组不同的任务
  5. The order and number of tasks is known in advance. 任务的顺序和数量是事先已知的。

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.

相关问题 如何提取order by子句,以便我可以使用逻辑来设置它? - How to extract an order by clause so I can use logic to set it? 如何在两个任务之间设置延迟? - How to put a delay between 2 tasks? 如何限制 C# 中的任务数量,以便通过该数量的任务可以完成多项工作 - How to limit number of tasks in C# so that multiple works can be done through that number of tasks 任务完成时未处理 - Tasks not being processed as they complete 如何按FIFO顺序序列化等待任务 - How can I serialize awaitable tasks in FIFO order 如何按顺序等待 C# 任务,而不是并行等待? - How can I await C# tasks in order, and not in parallel? 如何创建自定义SynchronizationContext,以便我自己的单线程事件循环可以处理所有延续? - How do I create a custom SynchronizationContext so that all continuations can be processed by my own single-threaded event loop? 如何在C#中的代码行之间设置延迟? - How can I set delay between code lines in C#? 如何在 layout.html 中添加搜索栏,以便在 controller 中处理? - How to add a search bar to layout.html so that it is processed in the controller? 我怎样才能订购点列表,以便绘制的线不相交? - How can I order a list of Points so that no lines drawn intersect?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM