The usual problem with calling something like count++
from multiple threads (which share the count
variable) is that this sequence of events can happen:
- Thread A reads the value of
count
.
- Thread B reads the value of
count
.
- Thread A increments its local copy.
- Thread B increments its local copy.
- Thread A writes the incremented value back to
count
.
- Thread B writes the incremented value back to
count
.
This way, the value written by thread A is overwritten by thread B, so the value is actually incremented only once.
Your code adds locks around operations 1, 2 (get
) and 5, 6 (set
), but that does nothing to prevent the problematic sequence of events.
What you need to do is to lock the whole operation, so that while thread A is incrementing the value, thread B can't access it at all:
lock (progressLock)
{
progress.CurrentCount++;
}
If you know that you will only need incrementing, you could create a method on Progress
that encapsulates this.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…