2

I have a very simple for loop that looks like this

for(int i = 0; i< 26; i++)
{
    DoSomething(i);
}

The DoSomething function takes about ~3 minutes to execute. I want to write a for loop that calls DoSomething() every minute without waiting for the previous call to finish. I tried to do something like this:

Parallel.For(0, 26, i =>
{
    DoSomething(i);
    System.Threading.Thread.Sleep(60000);
}

But it does not work since it first does the call and then sleeps. Reversing the steps also means that the DoSomething method calls fire without delay in between each call. How do I set it up so that the call to DoSomething is every minute?

Thanks!

Matt Kagan
  • 611
  • 1
  • 12
  • 24
  • 1
    Why not just use a [Timer](https://msdn.microsoft.com/en-us/library/system.timers.timer%28v=vs.110%29.aspx)? – Michael Todd May 28 '15 at 17:33
  • So you want something to be processed in parallel and after a particular time interval? Correct? If yes, see @MichaelTodd 's comment. – vendettamit May 28 '15 at 17:38

2 Answers2

5

You can use Task.Delay, which internally uses a Timer object:

public async Task DoSomethingAndWaitAsync()
{
    int i = 0
    while (i < 26)
    {
        Task.Run(() => DoSomething(i));
        await Task.Delay(TimeSpan.FromMinutes(1));

        i++;
    }
}

Or if you want to keep the for loop:

public async Task DoSomethingAndWaitAsync()
{
    for (int i = 0; i < 26; i++)
    {
        Task.Run(() => DoSomething(i));
        await Task.Delay(TimeSpan.FromMinutes(1));
    }
}
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
  • @YuvalItzchakov Can you help me with this: https://stackoverflow.com/questions/55026042/wait-for-response-from-the-serial-port-and-then-send-next-data – Prashant Pimpale Mar 11 '19 at 09:23
2
for (int i = 0 ; i < 26 ; i++)
{
    Task.Run(
        () =>
        {
            DoSomething(i);
        }
    );

    Thread.Sleep(TimeSpan.FromMinutes(1));
}
glenebob
  • 1,943
  • 11
  • 11
  • Whether or not you view this as "wasting" a thread depends on context, and adding async/await as needed is trivial. – glenebob May 28 '15 at 19:34