Why does Interlocked.Exchange not support Boolean type?

前端 未结 3 1749
醉话见心
醉话见心 2021-02-03 16:33

Is there some practical reason why the .NET team decided not to support Boolean in Interlocked.Exchange operation?

One of the usage examples is when you want to guarantee

3条回答
  •  一生所求
    2021-02-03 17:24

    Not answering the question, but as a workaround you can just use int instead of bool the way C does.

        int m_IsFirstTime = 1; // 1 means true 0 means false. 
    
        void SomeMethod()
        {
            if (1 == Interlocked.Exchange(ref m_IsFirstTime , 0))
                // Do something for the first time.
    
            else
                // Do something for all other times.
    
        }
    

    P.S. If there is evidence that read is faster than write then Interlocked.CompareExchange might be better for this case (only one first time and I assume a lot of non first).

提交回复
热议问题