|
分類:[.NET 全般]
c#の以下のコードで、Dictionaryにlockがかからない理由を教えてください。
以下コード-------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Text;
using System.Threading;
namespace ConsoleApplication1 { class Program { private static Dictionary<string, List<string>> test_dict = new Dictionary<string, List<string>>();
static void Main(string[] args) { List<string> test_list1 = new List<string>(); test_list1.Add("aaa"); test_list1.Add("bbb"); test_list1.Add("ccc");
List<string> test_list2 = new List<string>(); test_list2.Add("dd"); test_list2.Add("ee"); test_list2.Add("xx"); test_list2.Add("yy");
List<string> test_list3 = new List<string>(); test_list3.Add("ffff"); test_list3.Add("gggg"); test_list3.Add("hhhh"); test_dict.Add("key01", test_list1); test_dict.Add("key02", test_list2); test_dict.Add("key03", test_list3);
Thread thread1 = new Thread(new ThreadStart(ThreadMethod1)); thread1.Start();
Thread thread2 = new Thread(new ThreadStart(ThreadMethod2)); thread2.Start();
Console.ReadLine(); } private static void ThreadMethod1() { Console.WriteLine(DateTime.Now.ToString() + " [ThreadMethod1] start"); lock (test_dict) { Thread.Sleep(3000); } Console.WriteLine(DateTime.Now.ToString() + " [ThreadMethod1] end"); }
private static void ThreadMethod2() { Console.WriteLine(DateTime.Now.ToString() + " [ThreadMethod2] start"); lock (test_dict) { test_dict.Remove("key02"); } Console.WriteLine(DateTime.Now.ToString() + " [ThreadMethod2] test_dict.Remove(key02)"); Console.WriteLine(DateTime.Now.ToString() + " [ThreadMethod2] end"); } } }
|