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!
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.
*&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 .
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.
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With