There is one problem and one potential problem that I see in your code:
All threads are accessing recordCount
variable directly. Although num++
may look like an atomic operation, it is not. It is essentially equivalent to num = num + 1
. Since this is executed in several CPU instructions, it is possible that a thread takes a value, and gets suspended before updating the value. In mean time, other threads increase the value, and once initial thread is resumed, it just places value it calculated based on old starting value. Instead of using incrementing operator, you should use Interlocked.Increment()
function.
Interlocked.Increment(ref recordCount);
Enumerator of your collection may not be thread safe. If you are using a custom collection type parallel access to elements may iterate over them faster than you expect. This shouldn't cause problem you described though. It would be wise that you use BlockingCollection<T>
.