David Moles
David Moles

Reputation: 51103

Atomic read-modify-write in C#

I've seen a couple of places quoting the following bit of the C# spec: "Aside from the library functions designed for that purpose, there is no guarantee of atomic read-modify-write." Can somebody point me to these library functions?

Upvotes: 3

Views: 960

Answers (2)

Aaron McIver
Aaron McIver

Reputation: 24713

The Interlocked class should provide you with what you are looking for; such as Increment and Decrement.

Upvotes: 4

Dan Tao
Dan Tao

Reputation: 128327

I think it's referring to functions such as Interlocked.CompareExchange.

This method can be used to, e.g., atomically update a double:

static void Add(ref double field, double amount)
{
    double before, after;
    do
    {
        before = field;
        after = before + amount;
    }
    while (Interlocked.CompareExchange(ref field, after, before) != before);
}

Upvotes: 3

Related Questions