加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 多线程:锁定属性 – 这是正确的吗?

发布时间:2020-12-15 19:50:06 所属栏目:百科 来源:网络整理
导读:我写了以下代码: static readonly object failedTestLock = new object();public static Dictionarystring,Exception FailedTests{ get { lock (failedTestLock) { return _failedTests; } } set { lock (failedTestLock) { _failedTests = value; } }}publ
我写了以下代码:

static readonly object failedTestLock = new object();

public static Dictionary<string,Exception> FailedTests
{
    get
    {
        lock (failedTestLock)
        {
            return _failedTests;
        }
    }
    set
    {
        lock (failedTestLock)
        {
            _failedTests = value;
        }
    }
}

public void RunTest(string testName)
{
    try
    {
        //Run a test
    }
    catch (Exception exception)
    {
        // ?? Is this correct / threadsafe?
        FailedTests.Add(testName,exception);
    }
}

题:
这是将失败的测试安全地添加到字典中的正确方法吗?
这线程安全吗?
是FailedTests.Add调用INSIDE锁定还是OUTSIDE锁定?

你能解释为什么这是正确的/线程安全的,或者为什么不呢?

提前致谢

解决方法

上面代码的基本问题是,当线程获取字典或设置字典时,它只锁定对_failedTests的访问.只有一个线程可以一次获得对字典的引用,但是一旦线程具有对字典的引用,它就可以读取和操作它而不受锁的约束.

Is this a correct manner to safely add
the failed test to the Dictionary?

不,如果两个线程同时尝试添加到字典中,请不要这样做.如果您希望读取和写入按特定顺序发生,也不会发生.

Is this threadsafe?

It depends what you mean by threadsafe,但不,没有任何合理的定义.

Is FailedTests.Add called INSIDE the
lock or OUTSIDE the lock?

字典检索(get访问器)发生在锁内.此代码在释放锁之后调用Add.

Can you explain why this is correct/threadsafe or why not?

如果多个线程同时在您的字典上运行,则无法预测这些线程将更改其内容的顺序,并且您无法控制何时将进行读取.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读