c# - 锁语句饱和

标签 c# multithreading locking

我有这个代码:

class Program
{
    static void Main(string[] args)
    {
        TestClass instanceOfClass = new TestClass();
        while (true)
        {
            Thread threadTest = new Thread(new ParameterizedThreadStart(AddNewToClass));
            threadTest.Start(instanceOfClass);
        }
    }
    static void AddNewToClass(object parameter)
    {
        var instance = (TestClass)parameter;
        while (true)
        {
            if (instance.Contains(1))
            {
                continue;
            }
            else
            {
                instance.AddNew(1);
            }
        }
    }
}

class TestClass
{
    public Dictionary<int, string> dictionary;
    public TestClass()
    {
        dictionary = new Dictionary<int, string>();
    }
    public void AddNew(int test)
    {
        lock (dictionary)
        {
            dictionary.Add(test, "Test string");
        }
    }
    public bool Contains(int test)
    {
        lock (dictionary)
        {
            if (dictionary.ContainsKey(test))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}

我想做的是有几个不同的线程,从字典中添加/删除对象。我尝试运行它,但出现此异常:

An item with the same key has already been added.

这看起来非常奇怪。据我所知,lock 语句应该阻止有问题的字典,并且 TestClass.Contains(1) 应该总是返回 true,并且它抛出一个异常,因为它返回 true 不止一次(因此异常).

有人知道为什么会这样吗?谢谢

最佳答案

您的Contains() 方法是原子的。您的 Add() 方法也是如此。但是,AddNewToClass() 不是。一个线程可能会从 Contains() 得到一个结果...但无法保证它何时可能会或可能不会暂停(或恢复)。

那是你的比赛条件。

关于c# - 锁语句饱和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11751108/

相关文章:

java - 我如何检测我的方法在等待什么?

C# System.Security.Cryptography - 为什么指定 key 和 IV 两次?

c# - XNA C#SoundEffectInstance-没有声音

java - 随着线程数量的增加,Levenshtein 距离的并行实现速度会变慢

c# - 在任何情况下,在 ReaderWriterLockSlim 上调用 EnterWriteLock 应该进入读锁吗?

c# - 如何在构造函数中正确实例化静态 HttpClient

c# - 如何在 C# 中编写条件锁?

c# - 用另一个覆盖授权过滤器

c# - C#发布的程序.exe和dll,在启动时可以在我的计算机上运行,​​但不能在其他计算机上运行

python - 如何测试 Python http.server.HTTPServer 是否永远服务?