我试图重现不“保存线程”的字典行为并实现了示例(见下文)。我预计会出现死锁,但测试工作没有任何问题。请您帮忙解释一下我的测试中有什么问题以及如何模拟多线程字典错误。
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);
}
);
}
}
}