When developing multi-threaded software or using parallel programming techniques, it is essential that classes remain thread-safe. The Interlocked class provides methods that assist with thread safety by performing atomic operations. 

Thread-Safety

When you are using the task parallel library to parallelise your code, or when writing multi-threaded applications, you must ensure that your code is thread-safe. This means that any data that is shared by multiple threads must be accessed in a manner that ensures that threads cannot interfere with each other's results.

Some standard operations provided by C# and the .NET framework are not thread-safe, even though they may appear to be. For example, you might assume that the increment operator(++) performs an atomic operation. However, in reality incrementing a variable's value involves reading the value, updating the read value and writing the updated value back into the variable. If two threads attempt to increment a value simultaneously a race condition may occur and it is possible that the value be increased only by one, rather than two.

To demonstrate this problem, and for the other examples in this article, we will use methods from the Parallel class. To begin, create a console application and add the following using directives to the code. NB: If you are using an earlier version of the .NET framework than 4.0, you can create similar examples using standard multi-threading code. (4.0之前的版本没有并行计算功能)

using System.Threading;
using System.Threading.Tasks;

The following code executes a parallel for loop with one million increment operations, each changing the value of a shared variable. The final value of the variable should be one million. However, on a computer with multiple cores or processors, you will likely see a much lower result, caused by the increment operator not being thread-safe.

int total = 0;
Parallel.For(0, 1000000, i =>
{
    total++;
});
Console.WriteLine(total);   // Unlikely to be 1,000,000(结果不会是1,000,000)

相关文章: