Which one should be used in multi-thread time?
_counter += 1
OR
Interlocked.Increment(ref _counter)
.
public class Demo
{
public void Main()
{
for (int i = 0; i < 5; i++)
{
new Thread(() => FuncA()).Start();
}
}
private int _counter;
public void FuncA()
{
lock (this) //lock or Monitor or Mutex or Semaphore ...
{
_counter += 1;
//OR
Interlocked.Increment(ref _counter);
}
}
}
You don't need both lock
and Interlocked.Increment
use one or another, not both. If the goal is to only increment the counter then Interlocked.Increment
should be the preferable option.
From the docs for Interlocked.Increment
(emphasis mine):
Increments a specified variable and stores the result, as an atomic operation.
Which means it is already thread-safe and does not require additional locking.
Notes:
lock (this)
- please see Why is lock(this) {...} bad?
The question is tagged with ASP.NET so there is a chance the both are not enough. Both approaches provide guarantees only for single process, if you have several application running you might require some kind of distributed lock based on the actual task.