-
Notifications
You must be signed in to change notification settings - Fork 934
/
Copy pathThreadSafeDictionaryFixture.cs
109 lines (104 loc) · 3.21 KB
/
ThreadSafeDictionaryFixture.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
using System;
using System.Collections.Generic;
using System.Threading;
using log4net;
using NHibernate.Util;
using NUnit.Framework;
namespace NHibernate.Test.UtilityTest
{
[TestFixture]
public class ThreadSafeDictionaryFixture
{
public ThreadSafeDictionaryFixture()
{
log4net.Config.XmlConfigurator.Configure();
}
private static readonly ILog log = LogManager.GetLogger(typeof(ThreadSafeDictionaryFixture));
private readonly Random rnd = new Random();
private int read, write;
[Test, Explicit]
public void MultiThreadAccess()
{
MultiThreadRunner<IDictionary<int, int>>.ExecuteAction[] actions =
new MultiThreadRunner<IDictionary<int, int>>.ExecuteAction[]
{
delegate(IDictionary<int, int> d)
{
try
{
log.DebugFormat("T{0} Add", Thread.CurrentThread.Name);
write++;
d.Add(rnd.Next(), rnd.Next());
}
catch (ArgumentException)
{
// duplicated key
}
},
delegate(IDictionary<int, int> d)
{
log.DebugFormat("T{0} ContainsKey", Thread.CurrentThread.Name);
read++;
d.ContainsKey(rnd.Next());
},
delegate(IDictionary<int, int> d)
{
log.DebugFormat("T{0} Remove", Thread.CurrentThread.Name);
write++;
d.Remove(rnd.Next());
},
delegate(IDictionary<int, int> d)
{
log.DebugFormat("T{0} TryGetValue", Thread.CurrentThread.Name);
read++;
int val;
d.TryGetValue(rnd.Next(), out val);
},
delegate(IDictionary<int, int> d)
{
try
{
log.DebugFormat("T{0} get_this[]", Thread.CurrentThread.Name);
read++;
int val = d[rnd.Next()];
}
catch (KeyNotFoundException)
{
// not foud key
}
},
delegate(IDictionary<int, int> d)
{
log.DebugFormat("T{0} set_this[]", Thread.CurrentThread.Name);
write++;
d[rnd.Next()] = rnd.Next();
},
delegate(IDictionary<int, int> d)
{
log.DebugFormat("T{0} Keys", Thread.CurrentThread.Name);
read++;
IEnumerable<int> e = d.Keys;
},
delegate(IDictionary<int, int> d)
{
log.DebugFormat("T{0} Values", Thread.CurrentThread.Name);
read++;
IEnumerable<int> e = d.Values;
},
delegate(IDictionary<int, int> d)
{
log.DebugFormat("T{0} GetEnumerator", Thread.CurrentThread.Name);
read++;
foreach (KeyValuePair<int, int> pair in d)
{
}
},
};
MultiThreadRunner<IDictionary<int, int>> mtr = new MultiThreadRunner<IDictionary<int, int>>(20, actions);
IDictionary<int, int> wrapper = new ThreadSafeDictionary<int, int>(new Dictionary<int, int>());
mtr.EndTimeout = 2000;
mtr.Run(wrapper);
log.DebugFormat("{0} reads, {1} writes -- elements {2}", read, write, wrapper.Count);
}
}
}