Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to make this c# class thread safe without rewriting?

I love the quick way of creating classes in C# where we can easily create Members without having to implement the get and set code but (as far as I know) they are not thread safe!

public class SocksEntry
{
    public int Int1 { get; set; }
    public int Int2 { get; set; }
}

Does C# provide a quick an easy way of adding thread safety without having to do this?

public class SocksEntry
{
    protected object _lock = new object();

    // internal
    private int _int1 = 0;
    private int _int2 = 0;

    // accessors
    protected int Int1
    {
        get { lock (_lock) return _int1; }
        set { lock (_lock) _int1 = value; }
    }

    protected int Int2
    {
        get { lock (_lock) return _int2; }
        set { lock (_lock) _int2 = value; }
    }
}

It obviously makes the whole class a lot bigger and a pain to create compared to the non-thread safe version!

like image 330
antfx Avatar asked Dec 26 '12 15:12

antfx


People also ask

Can you use this in C?

In C you do not have the this keyword. Only in C++ and in a class, so your code is C and you use your this variable as a local method parameter, where you access the array struct.

WHAT IS &N in C?

*&n is equivalent to n . Thus the value of n is printed out. The value of n is the address of the variable p that is a pointer to int .

Is there an alternative to C?

The best alternative is Java. It's not free, so if you're looking for a free alternative, you could try C++ or Rust. Other great apps like C (programming language) are Go (Programming Language), C#, Lua and Perl.


Video Answer


2 Answers

Making a class thread safe is a lot harder than you might even imagine. It might not be enough to put locks around the getters and setters. So the best practice is to have the class not-thread safe and leave the responsibility to the consumer of this class to synchronize the access to it if he needs thread safety. If the consumer doesn't need thread safety, then great, you won't be penalizing the performance of the application just because you built thread safety into the class without even needing it. Why do you think that 99.99% of the classes in .NET are not thread-safe?

like image 107
Darin Dimitrov Avatar answered Oct 16 '22 13:10

Darin Dimitrov


In a word, no.

Auto-implemented properties are great, but when one hits the limitations, that's it.

However, you could create a Visual Studio snippet (like prop) that would write the boiler-plate code for you.

like image 30
SWeko Avatar answered Oct 16 '22 14:10

SWeko