Are C# structs thread safe?

前端 未结 6 2037
感情败类
感情败类 2020-12-03 12:22

Is a C# struct thread-safe?

For example if there is a:

struct Data
{
    int _number;
    public int Number { get { return _number; } set { _number =         


        
6条回答
  •  余生分开走
    2020-12-03 13:03

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

提交回复
热议问题