【发布时间】:2013-08-12 07:13:21
【问题描述】:
我试图重现不“保存线程”的字典行为 并实施示例(见下文)。 我预计会出现死锁,但测试工作没有任何问题。 请您帮忙解释一下我的测试中有什么问题以及如何模拟多线程字典错误。
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);
}
);
}
}
}
【问题讨论】:
-
首先删除 Sleep(),但它仍然无法执行您想要的操作。不安全 -> 竞争条件 -> 未定义的行为。您可以预期会出现各种错误,但不会出现死锁。
-
我在没有睡眠的情况下开始测试:没有任何错误
-
我的生产代码中有一个“死锁”问题(似乎在 Get from Dictionaty 中)。现在我调查这个问题。
-
除非您正在锁定,否则您不会出现死锁。此外,你为什么不使用
ConcurrentDictionary? -
在使用 ConcurrentDictionary 之前我想模拟我的问题。
标签: c# multithreading testing dictionary