C# and thread-safety of a bool

前端 未结 2 587
忘掉有多难
忘掉有多难 2020-12-09 16:14

I am very confused about this subject - whether reading/toggling a bool value is thread-safe.

    // case one, nothing
    private bool v1;
    public bool V         


        
2条回答
  •  轮回少年
    2020-12-09 16:36

    A little bit late but should be useful to the others.

    You can implement your own thread safe boolean in the following way:

    // default is false, set 1 for true.
    private int _threadSafeBoolBackValue = 0;
    
    public bool ThreadSafeBool
    {
        get { return (Interlocked.CompareExchange(ref _threadSafeBoolBackValue, 1, 1) == 1); }
        set
        {
            if (value) Interlocked.CompareExchange(ref _threadSafeBoolBackValue, 1, 0);
            else Interlocked.CompareExchange(ref _threadSafeBoolBackValue, 0, 1);
        }
    }
    

    Be sure to use Property everywhere, never access int variable directly.

提交回复
热议问题