c# - 如何模拟不是 "safe thread"字典的行为?

标签 c# multithreading testing dictionary

我试图重现不是“保存线程”字典的行为 并实现示例(见下文)。 我预计会出现死锁,但测试没有任何问题。 请你帮忙解释一下我的测试有什么问题以及如何模拟多线程字典错误。

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace parallelTest
{
    [TestClass]
    public class UnitTest1
    {
        Dictionary<int, string> dictionary = new Dictionary<int, string>();
        [TestMethod]
        public void TestMethod1()
        {
            dictionary[2000] = "test";

            Parallel.For(0, 1000, i =>
            {
                string value;
                dictionary.TryGetValue(2000, out value);
                dictionary[2000] = String.Format("new value {0}", i);
                dictionary.Add(i, String.Format("{0}", i));
                Trace.WriteLine(String.Format("thread: {0}, {1}, {2}", Thread.CurrentThread.ManagedThreadId, i, value));
                Thread.Sleep(100);
            }
            );
        }
    }
}

最佳答案

你不会面临死锁,因为 Dictionary 不会锁定其内部数据。
不过,您最终可能会在字典中得到意想不到的数据。在这种情况下:未添加的项目。

在压力测试后,您需要检查字典是否符合您的预期。

for(Int32  index=0; index < 1000; index++)
{
    if(dictionary.Values.Any(index.ToString()) ==  false)
    {
          // problem
    }

}

顺便说一句,如果你想强调一个字典,你需要删除函数中的所有其他操作,例如字符串.格式。通过这样做,您将增加在字典中制造问题的机会。

这是调用公共(public)添加方法时调用的内部方法,如您所见,其中没有锁。

private void Insert(TKey key, TValue value, bool add)
{
    if (key == null)
    {
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
    }
    if (this.buckets == null)
    {
        this.Initialize(0);
    }
    int num = this.comparer.GetHashCode(key) & 2147483647;
    int num2 = num % this.buckets.Length;
    int num3 = 0;
    for (int i = this.buckets[num2]; i >= 0; i = this.entries[i].next)
    {
        if (this.entries[i].hashCode == num && this.comparer.Equals( this.entries[i].key
                                                                   , key))
        {
            if (add)
            {
                ThrowHelper.ThrowArgumentException(ExceptionResource
                                                      .Argument_AddingDuplicate);
            }
            this.entries[i].value = value;
            this.version++;
            return;
        }
        num3++;
    }
    int num4;
    if (this.freeCount > 0)
    {
        num4 = this.freeList;
        this.freeList = this.entries[num4].next;
        this.freeCount--;
    }
    else
    {
        if (this.count == this.entries.Length)
        {
            this.Resize();
            num2 = num % this.buckets.Length;
        }
        num4 = this.count;
        this.count++;
    }
    this.entries[num4].hashCode = num;
    this.entries[num4].next = this.buckets[num2];
    this.entries[num4].key = key;
    this.entries[num4].value = value;
    this.buckets[num2] = num4;
    this.version++;
    if (num3 > 100 && HashHelpers.IsWellKnownEqualityComparer(this.comparer))
    {
        this.comparer = (IEqualityComparer<TKey>)HashHelpers
                                    .GetRandomizedEqualityComparer(this.comparer);
        this.Resize(this.entries.Length, true);
    }
}

希望对你有帮助。

关于c# - 如何模拟不是 "safe thread"字典的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18181365/

相关文章:

c# - 将数据动态添加到 GridView 内的 asp 文字控件

c# - 在 ASP.NET 中使用带有 join 的 where 子句

c# - 显示 ComboBoxItem 的工具提示 - 移动鼠标后有效,但不是第一次尝试

c# - .net-4.6 中的异步 Thread.CurrentThread.CurrentCulture

java - 寻找竞争条件

java - 目前在 Java 中可以实现的最低 TCP 延迟是多少?

java - 如何使用 Rest assured 验证数组中元素的正确值

testing - 等待一个链接出现,该链接已经在 selenium 的页面中

c# - Asp.net MVC 多用户 session /用户模拟

iphone - iPhone 中的 iAd 集成