Are C# structs thread safe?

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).

Leave a Comment