1

I am trying to loop through a list of tasks and offset the start of each task by a specific amount of seconds like:

Int32 delayTime = 1500;

List<Task> tasks = new List<Task>();
// .... add stuff to task list.
tasks.ForEach(task =>
{
    Task.Delay(delayTime);
    task.Start();
    delayTime += 1500;
});

However, the above starts all tasks together not taking in account the task delay. Is there a way to stagger a list of tasks, or structure it differently so I can start each task a few seconds after the previous one starts?

dee-see
  • 23,668
  • 5
  • 58
  • 91
Joshua Wieczorek
  • 655
  • 2
  • 9
  • 23

1 Answers1

3

Task.Delay "Creates a cancellable task that completes after a specified time interval." (source). So basically your ForEach loop starts a new Task that is going to wait for delayTime on its own thread and then you start task immediately after starting that delay.

You should either await that Task.Delay call

Int32 delayTime = 1500;

List<Task> tasks = new List<Task>();
// .... add stuff to task list.
tasks.ForEach(async task =>
{
    await Task.Delay(delayTime);
    task.Start();
    delayTime += 1500;
});

use Task.Delay(delayTime).Wait()

Int32 delayTime = 1500;

List<Task> tasks = new List<Task>();
// .... add stuff to task list.
tasks.ForEach(task =>
{
    Task.Delay(delayTime).Wait();
    task.Start();
    delayTime += 1500;
});

or use Thread.Sleep(delayTime) to put the current thread to sleep.

Int32 delayTime = 1500;

List<Task> tasks = new List<Task>();
// .... add stuff to task list.
tasks.ForEach(task =>
{
    Thread.Sleep(delayTime);
    task.Start();
    delayTime += 1500;
});

See this SO question to know when you should use Delay vs Sleep.

dee-see
  • 23,668
  • 5
  • 58
  • 91
  • Thank you. I was missing the .Wait(). Now it is working. I did not want to put the actual thread to sleep in fear it may stop another task running on the same thread. – Joshua Wieczorek Nov 17 '18 at 00:36