什么是Java的getAndSet的c#等价物

Uro*_*ros 1 c# multithreading

我想编写与此java代码类似的c#代码:

public class Syncer {
    private AtomicBoolean syncInProgress = AtomicBoolean(false);

    // Data is synced periodically and on user request
    // and these two calls may overlap
    public void SyncData() {
        if (flag.getAndSet(true)) {
            return ;
        }

        // Sync data...
        // It is enough that one thread is syncing data

        flag.getAndSet(false);
    }
}
Run Code Online (Sandbox Code Playgroud)

xan*_*tos 6

我同意克里斯,Interlocked.Exchange(ref Int32,?Int32)只用0,1是替代品.

方法描述:

将32位有符号整数设置为指定值,并将原始值作为原子操作返回.

描述AtomicBoolean.getAndSet():

以原子方式设置为给定值并返回先前的值.

可悲的是没有Interlocked.Exchange()bool(并注意Interlocked.Exchange<T>()是引用类型!)

问题中给出的代码:

public class Syncer
{
    private int flag = 0;

    // Data is synced periodically and on user request
    // and these two calls may overlap
    public void SyncData()
    {
        if (Interlocked.Exchange(ref flag, 1) == 1)
        {
            return;
        }

        // Sync data...
        // It is enough that one thread is syncing data

        Interlocked.Exchange(ref flag, 0);
    }
}
Run Code Online (Sandbox Code Playgroud)