user1766169
user1766169

Reputation: 1987

C# Thread safe code

Is this code thread safe?

DoStuff is called in a new thread using Task.

Task.Factory.StartNew(() => DoStuff());


private void DoStuff()
{
    List<SalesRecord> salesRecords = new List<SalesRecord>();
    SalesRecord salesRecord1 = new SalesRecord {Amount = 10.0, Sales = 1};
    SalesRecord salesRecord2 = new SalesRecord {Amount = 15.0, Sales = 1};
    SalesRecord salesRecord3 = new SalesRecord {Amount = 1.0, Sales = 2};
    salesRecords.Add(salesRecord1);
    salesRecords.Add(salesRecord2);
    salesRecords.Add(salesRecord3);
    SalesRecord result = Util.SumSales(salesRecords);
}

A struct just to store data:

public struct SalesRecord
{
    public uint Sales;
    public double Amount;
}

stuff

public static class Util
{
    public static SalesRecord SumSales(List<SalesRecord> records)
    {
        SalesRecord result = new SalesRecord();

        result.Amount = records.FindAll(record => (record.Sales == 1)).Sum(record => record.Amount);
        result.Sales = 1;
        return result;
    }
}

Upvotes: 1

Views: 493

Answers (3)

Josh L.
Josh L.

Reputation: 454

Posted for those trying to figure out why it's thread-safe even with a static method

In this particular case, access to Util.SumSales(salesRecords) is thread safe as it is a thread-local method (the thread that calls this method provides it's own copy of the data to the method and data access in that thread is exclusive to the thread that called it).

When you call the following code:

Task.Factory.StartNew(() => DoStuff());

You assign a new thread to handle DoStuff(). Everything that happens in DoStuff (unless you introduce variables that could be manipulated outside of it) is exclusive to that new thread.

I assume you'll do more with what you get from DoStuff(). In that case, you should store your results in Concurrent Collections.

Upvotes: 0

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73462

Is this code thread safe?

Yes, it is. This code doesn't use any shared state. By definition code which doesn't uses any shared state is thread-safe.

You can call DoStuff concurrently in any number of threads without any problem. That said, DoStuff method isn't very useful though.

Upvotes: 9

Shar1er80
Shar1er80

Reputation: 9041

Your code looks fine. Even if DoStuff is being launched via Task, I don't see anywhere in your code where you're dealing with class variables, they're all local variables.

Reference: C# : What if a static method is called from multiple threads?

Upvotes: 4

Related Questions