How to delay 'hot' tasks so they can processed in a set order

后端 未结 2 884
伪装坚强ぢ
伪装坚强ぢ 2021-01-15 23:28

Say I have a set of tasks:

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


        
相关标签:
2条回答
  • 2021-01-15 23:57

    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. 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();
    
    0 讨论(0)
  • 2021-01-16 00:08

    you can simply create tasks with its constructor and then, call execution with .Start() methods.

    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;
    }
    
    0 讨论(0)
提交回复
热议问题