user6313890
user6313890

Reputation:

Perform multiple actions in same time

I want to perform multiple loops in the same time using async Task (I don't want use Parallel.ForEach)

I do :

static async void Run()
{
    await MultiTasks();
}

static async Task MultiTasks()
{
    var Loop1 = Loop1Async();
    var Loop2 = Loop2Async();

    await Loop1;
    await Loop2;
}

static async Task Loop1Async()
{
    for (int i = 0; i < 500; i++)
    {
        Console.WriteLine("Loop 1 : " + i);
    }
}

static async Task Loop2Async()
{
    for (int i = 0; i < 500; i++)
    {
        Console.WriteLine("Loop 2 : " + i);
    }
}

Run() is called in my Main method.

But the two loop is not executed in the same time. Once the first lap is completed, the second begins

Why and how to do this ?

Upvotes: 0

Views: 1890

Answers (4)

alltej
alltej

Reputation: 7285

Your Loop1Async and Loop2Async methods does not have an await inside. For a method to be async it needs to have 1 or more await

Upvotes: 0

Eric Lippert
Eric Lippert

Reputation: 660159

You have the fundamental misunderstanding common to beginner users of await.

Let me be very clear about this. Await does not make something asynchronous. It asynchronously waits for an asynchronous operation to complete.

You are awaiting a synchronous operation. There is absolutely nothing asynchronous about the methods you are calling; await does not make them asynchronous. Rather, if they were asynchronous, then the await would return control to the caller immediately, so that the caller could continue to do work. When the asynchronous work finishes, then at some point in the future the remainder of the method is executed, with the awaited result.

Upvotes: 6

Matthew Whited
Matthew Whited

Reputation: 22443

Try .WhenAll(...)

static async Task MultiTasks()
{
    var Loop1 = Loop1Async();
    var Loop2 = Loop2Async();

    await Task.WhenAll(Loop1, Loop2);
}

As others have noted your async methods do not currently yield execution.

You need something that will allow threads to yield back to the system so they can actually run in parallel. Something like this...

static async Task Loop1Async()
{
    for (int i = 0; i < 500; i++)
    {
        Console.WriteLine("Loop 1 : " + i);
        await Task.Yield();
    }
}

static async Task Loop2Async()
{
    for (int i = 0; i < 500; i++)
    {
        Console.WriteLine("Loop 2 : " + i);
        await Task.Yield();
    }
}

Upvotes: 1

Vladislav Borovikov
Vladislav Borovikov

Reputation: 128

Loop1Async and Loop2Async in fact are synchronous. Consider using WriteLineAsync method.

You can also use Task.WhenAll in MultiTasks.

Upvotes: 1

Related Questions