C#多线程代码发出破坏数据的问题

时间:2012-03-14 19:21:30

标签: c# multithreading locking

这真的非常接近真实的方法Bob posted我们所拥有的是与特定数据合并的模板。下面的代码试图重用我们已经构建的模板。因此,如果我们已经为“达拉斯”构建了一个模板,我们就可以重用它。我们看到的是“达拉斯”的模板,其中包含“NewYork”模板应具有的信息。当我们慢慢地逐步执行代码时,我们看不到它。我的想法是,下面的变量 sc 在被放入哈希表 genericTemplates 之前被另一个线程更改,所以当使用Dallas信息的线程准备插入时将信息输入 genericTemplaes 散列表使用NewYork的线程已经更改了 sc 中保存的数据以反映NewYork数据,但是标有Dallas“recordHash”密钥。像Bob一样,我不熟悉使用Lock语句并理解它是如何工作的。

我还被告知,线程范围内的任何变量只属于该线程。传递的全局变量或对象我需要关注它。有人可以验证吗。

private Template EnsureGenericTemplate(Detail details, Hashtable genericTemplates)
{
    Template return_Object = null;
    SectionContainer sc = null;
    StringBuilder htmlTemplate = null;
    string recordHash = string.Format("{0}_{1}_{2}", circleNumber, zipCode, topicCd);

    lock (genericTemplates) {
        hasTemplateDefined = genericTemplates.ContainsKey(recordHash);
    {

    if (!hasTemplateDefined)
    {
        templateData = getTemplateData();

        htmlTemplate = new StringBuilder(foo1.HtmlTemplate);

        HtmlParser = hp = new HtmlParser();
        sc = hp.parseNew(htmlTemplate.ToString(), false);

        //This method merges the html template with the template data based on <tags>
        htmlTemplate = BuildTemplate(sc, htmlTemplate.ToString(), templateData);

        //This method merges the html template with the template data base on %SomeVar%
        hp.parseProperties<Detail>(ref htmlTemplate, details, false);

        //Puts the htmlTemplate into an object that hold html and text
        foo2.Html = htmlTemplate.ToString();

        lock (genericTemplates)
        {
            if (!genericTemplates.ContainsKey(recordHash))
            {
                  return_Object = new Template(foo2, sc);
                  genericTemplates.Add(recordHash, Object_For_Reuse);
            }
        }
    }  

    if (htmlTemplate == null)
    {
        lock (genericTemplates)
        {
            if (genericTemplates.ContainsKey(recordHash))
                return_Object = (Template)genericTemplates[recordHash];
        }
    }
    return return_Object;
 }

1 个答案:

答案 0 :(得分:3)

您在genericTemplates上锁定了两次 - 这是不必要的。

不要使用Hashtable而是考虑使用专为多线程设计的集合,例如ConcurrentDictionary

http://msdn.microsoft.com/en-us/library/dd287191.aspx

我还建议阅读这本关于多线程的免费书 - 它充满了好的模式

http://www.albahari.com/threading/