Can someone either explain or point me to some documentation that can explain to me why this code doesn't throw any exceptions:
var d = new Dictionary<object, object>();
System.Threading.Tasks.Parallel.ForEach(new Action[] {
() => {
System.Threading.Tasks.Parallel.For(0, 1024, i => {
d.Add(new object(), new object());
});
},
() => {
System.Threading.Tasks.Parallel.For(0, 1024, i => {
d.TryGetValue(new object(), out _);
});
},
}, a => a());
I tried running this on my 8-core computer expecting something would throw an exception about an invalid operation or null reference, etc., but it never does. Though I end up with a dictionary that has the wrong number of elements, how is it that this doesn't throw and exception and/or crash?
Just because something isn't thread safe doesn't mean using it from multiple threads will cause it to throw an exception. The Dictionary<TKey, TValue> class is not thread safe and only expects to be used by one thread at a time. It likely doesn't include any checks for what threads are accessing it at the same time as that would be too expensive. It simply assumes that there is only one thread accessing it at a time.