kspearrin
kspearrin

Reputation: 10788

Async Multiple Tasks Threading Issue

I am attempting to execute multiple (n) tasks asynchronously which aggregate to a single summed result. Currently I have the following:

public class Foo
{
    public async void DoWork()
    {
        var stopwatch = Stopwatch.StartNew();
        List<Task> tasks = new List<Task>();

        var bar = new Bar();

        for (int i = 0; i < 20; i++)
        {
            var task = Task.Run(() =>
            {
                Thread.Sleep(500);

                bar.Count1++;
                bar.Count2++;
            });

            tasks.Add(task);
        }

        await Task.WhenAll(tasks.ToArray());

        Console.WriteLine("All done, Bar Count1: " + bar.Count1 + ", Count2: " + bar.Count2);
        stopwatch.Stop();
        Console.WriteLine("Time taken " + stopwatch.ElapsedMilliseconds + " ms");
    }
}

public class Bar
{
    public int Count1 { get; set; }
    public int Count2 { get; set; }
}

I would expect bar.Count1 and bar.Count2 to have values of 20 at the end of execution here, however, each time I run the program I get different values for each of them (which are most of the time < 20). How do I get around this problem?

Upvotes: 1

Views: 63

Answers (1)

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73502

Nothing closure problem here. ++ operator is not thread safe. So you need a lock around it.

lock(bar)
{    
    bar.Count1++;
    bar.Count2++;    
}

That should solve the problem.

Upvotes: 4

Related Questions