Is a C# struct thread-safe?
For example if there is a:
struct Data
{
int _number;
public int Number { get { return _number; } set { _number = value; } }
public Data(int number) { _number = number; }
}
in another type:
class DadData
{
public Data TheData { get; set; }
}
is property named TheData, thread-safe?
C++ was developed by Bjarne Stroustrup in 1979. C does no support polymorphism, encapsulation, and inheritance which means that C does not support object oriented programming. C++ supports polymorphism, encapsulation, and inheritance because it is an object oriented programming language. C is (mostly) a subset of C++.
While it's an integer, the %c interprets its numeric value as a character value for display. For instance for the character a : If you used %d you'd get an integer, e.g., 97, the internal representation of the character a. vs. using %c to display the character ' a ' itself (if using ASCII)
C language supports procedural programming. Whereas C# supports object oriented programming.
C+ (grade), an academic grade. C++, a programming language. C with Classes, predecessor to the C++ programming language. ANSI C, a programming language (as opposed to K&R C)
Well - best practice is that structs should always (except in a few very specific scenarios, and even then at risk) be immutable. And immutable data is always thread safe. So if you followed best practice and made this:
struct Data
{
readonly int _number;
public int Number { get { return _number; } }
public Data(int number) { _number = number; }
}
then yes; that is thread-safe. In all other cases the answer is "probably not".
Note also that atomicity rules apply, so even a single read or update to DadData.TheData
cannot be assumed to be thread-safe, even with an immutable struct. You could (especially for oversized structs) have one thread reading the struct while another thread re-writes it; without synchronization bad things will happen (eventually).
No, structures in .NET are not intrinsically thread-safe.
However, the copy-by-value semantics that structures have great relevance to this converation.
If you are passing your structures around and assigning them in some way to variables or pass-by-value parameters (no ref or out keywords) then a copy is being used.
Of course, this means that any changes made to the copy are not reflected in the original structure, but it's something to be aware of when passing them around.
If you are accessing the structure directly in a manner that doesn't involve copy-by-value semantics (e.g. accessing a static field which is the type of the structure, and as Marc Gravel points out in his answer, there are many other ways) across multiple threads, then you have to take into account the thread-safety of the instance.
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