Fernando Silva Fernando Silva - 3 months ago 26
C# Question

How to make parallel async and await use 100% of the cpu?

I have searched a lot of codes saying that is possible to use multiple cores with parallel async, but none worked. It is always stuck in a single core.

Is it possible?

This is uses 100% of the cpu:

class Program
{
static void Main(string[] args)
{
Parallel.For(0, 100000, p =>
{
while (true) { }
});
}
}


Using parallel async, I dont get more than 12%:

class Program
{
static void Main(string[] args)
{
Task.Run(async () =>
{
var tasks = Enumerable.Range(0, 1000000).Select(i =>
{
while (true) { }

return Task.FromResult(0);
});

await Task.WhenAll(tasks);
}).GetAwaiter().GetResult();
}
}


100% cpu. Thanks all that helped, and not just mocked or tried to close:

class Program
{
static void Main(string[] args)
{
Task.Run(async () =>
{
var tasks = new List<Task>();

for (int i = 0; i < 100; i++)
tasks.Add(Task.Run(() =>
{
while (true) { }
}));

await Task.WhenAll(tasks);
}).GetAwaiter().GetResult();
}
}

Answer

Your code only creates one task, Task.FromResult returns a finished task and it's added after the while loop, that will be executed 100000 times, but one after other as the generation is done by the synchronous function Select.

You can change your code to this:

class Program
{
    static void Main(string[] args)
    {

        var tasks = Enumerable.Range(0, 1000000).Select(i =>
        {
            return Task.Run(() =>
            {
                while (true) { }

                return 0;
            });
        });


        Task.WhenAll(tasks).GetAwaiter().GetResult();

    }
}

It will use the 100%, tested.

Comments