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

c# – 如何激发对共享资源的同时访问?

发布时间:2020-12-15 21:41:23 所属栏目:百科 来源:网络整理
导读:我正在创建一个对输入执行顺序处理的组件.由于它将托管在几个不同的进程中,我需要它是线程安全的.起初,我故意从代码中省略了线程安全性.现在是时候介绍一下了. 首先,我想引发一个错误,但是无法做到.以下是处理引擎代码的简化版本: public Document DoOrches
我正在创建一个对输入执行顺序处理的组件.由于它将托管在几个不同的进程中,我需要它是线程安全的.起初,我故意从代码中省略了线程安全性.现在是时候介绍一下了.

首先,我想引发一个错误,但是无法做到.以下是处理引擎代码的简化版本:

public Document DoOrchestration(Document input)
{
    Document output = new Document();

    foreach (var orchestrationStep in m_OrchestrationSteps)
    {
        var processor = GetProcessor(orchestrationStep).Clone();

        output = processor.Process(input);

        input = output;
    }

    return output;
}

处理器可以由我组织中的其他人开发,可以包括一些复杂的初始化.它们也可能是线程不安全的,所以我使用Prototype Pattern来获取它们的唯一实例,以避免线程问题.

为了测试这个功能,我使用了以下代码:

for (int i = 0; i < 20000; i++)
{
    Thread t = new Thread(() => TestOrchestration(i));
    t.Start();
}

void TestOrchestration(int number)
{
    Document doc = new Document(string.Format("Test {0}",number));
    doc = DoOrchestration(doc);
    if (doc.ToString().Substring(0,35) != strExpectedResult)
    {
        System.Console.WriteLine("Error: {0}",doc.ToString();
    }
}

我预计一些线程会与另一个线程发生冲突并混淆其结果,但令我惊讶的是,这并没有发生.

对此可能有一个简单而合理的解释,但它让我望而却步.或者只是代码太简单而导致两个线程同时摆弄输入/输出变量?

解决方法

查看 CHESS.

CHESS is a tool for finding and reproducing Heisenbugs in concurrent programs. CHESS repeatedly runs a concurrent test ensuring that every run takes a different interleaving. If an interleaving results in an error,CHESS can reproduce the interleaving for improved debugging. CHESS is available for both managed and native programs.

(编辑:李大同)

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

    推荐文章
      热点阅读