Pietr Podschinski
Pietr Podschinski

Reputation: 83

How to run multiple methods asynchron and in parallel with delay

I'm trying to run two methods in parallel. The first method connects to an ftp server and downloads some data. Because I want to reduce the network traffic it should run every 30 s. In parallel I want another method to run independent from the first method every 10 s.

The problem is I don't get the methods running/delayed in parallel.

namespace Example
{
    class Program
    {
        static async Task Main(string[] args)
        {
            await Task.Run(async () =>
            {
                while (true)
                {
                    await Every10s();
                    await Every30s();
                }
            });
        }

        public static async Task<bool> Every10s()
        {
            await Task.Delay(10000);
            Console.Writeline("10s");
            return true;
        }

        public static async Task<bool> Every30s()
        {
            await Task.Delay(30000);            
            Console.Writeline("30s");
            return true;
        }
    }
}

I would expect the following output with the corresponding pauses in between: 10s 10s 10s 30s 10s 10s 10s 30s ...

But instead both methods wait for each other so I get the output 10s 30s 10s 30s 10s 30s with a 40s pause.

Any help and hints are appreciated.

Upvotes: 3

Views: 490

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 456587

Because I want to reduce the network traffic it should run every 30 s. In parallel I want another method to run independent from the first method every 10 s.

You have two independent loops of work, so you need two loops in your code:

async Task RunEvery10s()
{
  while (true)
    await Every10s();
}

async Task RunEvery30s()
{
  while (true)
    await Every30s();
}

await Task.WhenAll(RunEvery10s(), RunEvery30s());

Upvotes: 4

Related Questions