To work around this situation, non-atomic operations can be secured by a lock statement. Locking is almost like a frame around these operations. Much faster and easier but it is through the use of Class Interlocked. The use of this class is not only more efficient than a lock, it also prevents blocking or displacing the thread. And finally, does Interlocked even across process boundaries, while the lock statement is only applicable to threads in the current process.
Code:
class Program {
static long sum;
static void Main () {
// Simple increment / decrement operations:
Interlocked.Increment (ref sum); // 1
Interlocked.Decrement (ref sum); // 0
// Add / subtract a value:
Interlocked.Add (ref sum, 3); // 3
// Read a 64-bit field:
Console.WriteLine (Interlocked.Read (ref sum)) // 3
// Write a 64-bit field while reading previous value:
// (This prints "3" while updating sum to 10)
Console.WriteLine (Interlocked.Exchange ref sum (, 10)) // 10
// Update a field value only if it matches (10):
Interlocked.CompareExchange (ref sum, 123, 10), // 123
}
}
Bookmarks