C#字典Dictionay多线程读是否是安全的
程序员文章站
2022-03-10 09:14:06
答案:是线程安全的,只读不写多线程下,完全不需要加锁! 测试代码: 模拟5万个线程读字典,看看是否混乱: 完全不需要担心,放心 ......
答案:是线程安全的,只读不写多线程下,完全不需要加锁!
测试代码:
using system; using system.diagnostics; using system.threading; using system.collections.generic; namespace hello { public class threadsafe { dictionary<int, int> dits = new dictionary<int, int>(); public threadsafe() { for (int i = 0; i < 100; i++) { dits.add(i, i); } } public void test(object i) { int t = convert.toint32(i); int v; thread.sleep(1); dits.trygetvalue(t, out v); if (!t.equals(v)) { console.writeline("i:{0},v:{1}", t, v); } } } }
模拟5万个线程读字典,看看是否混乱:
static void main(string[] args) { threadsafe ts = new threadsafe(); random random=new random(); console.writeline("hello world!2"); for (int i = 0; i < 50000; i++) { new thread(new parameterizedthreadstart(ts.test)).start(random.next(100)); } console.read(); }
完全不需要担心,放心