线程安全实现一次性方法

Vas*_*sya 1 .net c# multithreading thread-safety

我有一个方法,例如,必须被调用不超过一次Dispose.现在,我意识到它是下一个:

private bool _isAlive = true;

public void Dispose()
{
    if (this._isAlive)
    {
        this._isAlive = false;
        //Do Something
    }
}
Run Code Online (Sandbox Code Playgroud)

但它不是线程安全的,因为comprasion和setting flag之间存在间隙_isAlive为false.因此,可能有多个线程执行//Do Something代码.

它有线程安全的变体吗?

Yah*_*hia 5

使用(根据评论更新):

private long _isSomeMethodExecuted = 0;

public void Dispose()
{
 if ( Interlocked.Read ( ref this._isSomeMethodExecuted ) != 0 )
      return;

 if (Interlocked.Increment (ref this._isSomeMethodExecuted) == 1) //check if method is already executed
 {
        //Main code of method

 }
// leave the decrement out - this leads to 
// this method being callable exactly once as in the lifetime of the object
// Interlocked.Decrement (ref this._isSomeMethodExecuted);
}
Run Code Online (Sandbox Code Playgroud)

有关参考资料,请参阅http://msdn.microsoft.com/en-us/library/zs86dyzy.aspx

更新(根据@LukeH的评论):

单个CompareExchange呼叫更简单/更好:

public void Dispose() 
{ 
if (Interlocked.CompareExchange(ref _isSomeMethodExecuted, 1, 0) == 0) 
{ /* main code of method */ } 
}
Run Code Online (Sandbox Code Playgroud)