null values in List<string> when adding and removing in multiple threads
List<T>
is not thread-safe except for N reads and zero writes; any non-zero number of writes alongside anything else is not supported, and such behavior is completely undefined. If you need concurrency: either add synchronization, or use a concurrent collection type.
in addition to @Marc Gravell answer.
but I do not understand how these null values are generated
The first thread continuously adds "Test {i}"
. However, the next thread removes "Test {i}"
. Therefore, Those null values are as a result of removal action of the next thread.
of worth to say that, next "Test {i}"
won't be replaced to removed one but appended at the end of the generic collection.
The final result would behave like below:
Test 1 null Test 3 null null Test 6 .... Test 1 Test 2 null null Test 6 ...