For example I have var linkedList = new LinkedList<int>();
Then I add one node. linkedList.AddLast(1);
After that I have two threads respectively calling linkedList.AddLast(2); (same statement).
So can I safely expect it becomes 1->2->2 linked list?
Or it can become 1->2 when race condition happens?
(Maybe it also has visibility issue, but before that I firstly wonder if such race condition can happen.)
This is a question that can easily be answered with a quick little test app. The answer is 1->2 will happen sometimes.
private static void RunTest()
{
for (int i = 0; i < 100; i++)
{
var lst = new LinkedList<int>();
Parallel.For(1, 51, j =>
{
lst.AddLast(j);
});
if (lst.Count < 50)
{
Console.WriteLine(lst.Count);
}
}
}
As has been mentioned, this collection is not thread-safe. You will need to serialize the access or use a built-in thread-safe collection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With