stuck_inside_task
stuck_inside_task

Reputation: 303

Load testing with Task.Run() inside a loop vs WhenAll()

I wanted to do some simple load test on a piece of code I wrote with multiple threads hitting a piece of code at once.

Now the below code Sample #1 gave me the expected results. But I am not quite sure why Sample #2 didn't give me the same. Could someone explain, please?

Code sample #1

    private static FileCreator _fileCreater;
    public static void Main(params string[] args)
    {
        _fileCreater = new FileCreator();
        RunTasks().GetAwaiter().GetResult();
    }

    private static async Task RunTasks()
    {
        List<Task> tasks = new List<Task>();

        for (int i = 0; i < 100000; i++)
        {
            tasks.Add(Task.Run(() =>
            {
                _fileCreater.SaveMessage(new Message());
            }));
        }

        await Task.WhenAll(tasks);
    }

Initially, I had the below and I expected the same result, but what I noticed was my CPU never went past 20%, which suggested it wasn't really spanning up multiple threads

Code Sample #2

    private static FileCreator _fileCreater;
    public static void Main(params string[] args)
    {
        _fileCreater =  new FileCreator();
        RunTasks().GetAwaiter().GetResult();
    }

    private static async Task RunTasks()
    {
        for (int i = 0; i < 100000; i++)
        {
            await Task.Run(() =>
            {
                _fileCreater.SaveMessage(new Message());
            });
        }
    }

Upvotes: 0

Views: 405

Answers (1)

Milney
Milney

Reputation: 6417

Your second piece of code is awaiting each task... so no they will not be run concurrently, as you wait for each to finish before starting the next.

Upvotes: 2

Related Questions