在多个线程中添加和删除时 List<string> 中的 null 值

Seb*_* S. 5 c# multithreading list

我知道 C# System.Collections.Generic.List 对象不是线程安全的。但我想知道为什么这段代码会生成空值。

Task.Run(() =>
{
    for (var i = 0; i < 10; i++)
    {
        var str = $"Test {i}";
        list.Add(str);

        if (i == 9)
        {
            i = 0;
        }
    }
});

Task.Run(() =>
{
    while (true)
    {
        list.Remove("Test 1");
        list.Remove("Test 2");
        list.Remove("Test 3");
        list.Remove("Test 4");
        list.Remove("Test 5");
        list.Remove("Test 6");
        list.Remove("Test 7");
        list.Remove("Test 8");
        list.Remove("Test 9");
    }
});
Run Code Online (Sandbox Code Playgroud)

这是几秒钟后列表的一部分:

在此处输入图片说明

如果条目不存在于列表中,则负责从列表中删除条目的线程可能会崩溃。因此,出于其他多线程原因,我理解为什么没有从列表中删除某些对象,但我不明白这些空值是如何生成的。有没有人解释这些值是如何生成的?

Mar*_*ell 5

List<T>除了 N 次读取和零次写入之外,不是线程安全的;不支持任何非零数量的写入以及其他任何内容,并且这种行为完全未定义。如果需要并发:要么添加同步,要么使用并发集合类型。


Mr.*_*.AF 5

除了@Marc Gravell 的回答。

但我不明白这些空值是如何生成的

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 ...  
Run Code Online (Sandbox Code Playgroud)

  • 这就是我一直在寻找的答案。添加操作会分配内存的下一部分,而删除操作(几乎同时)会清除之前的内存,并且不会再次被覆盖。谢谢! (3认同)