Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to recreate "Index was outside the bounds of the array" adding items to Dictionary?

I'm consistenlty getting this error on a multithreading .net 3.5 application

ERROR 26 Exception thrown. Details: 'System.IndexOutOfRangeException: Index was outside the bounds of the array.

at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)

at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)

I think I know how to fix it (adding locks where appropiate) but I'd like to be able to recreate this problem on my local environment so I'll be sure that I fixed it and also I be able to add a unit test for it.

Do you know any consistent way to recreate this?

like image 882
StackOverflower Avatar asked Oct 05 '12 14:10

StackOverflower


2 Answers

Dictionary<string, string> dict = new Dictionary<string, string>();

Task.Factory.StartNew(() => { while (true) dict["a"] = "a"; });
Task.Factory.StartNew(() => { while (true) dict.Remove("a"); });
like image 68
L.B Avatar answered Sep 16 '22 16:09

L.B


Unfortunately, being consistent in a multithreaded application where race conditions occur is simply not achievable.

The hardware differences alone between your machine and the production one will ensure that when a problem does occur, it may not be in the same location. Even if the hardware is the same, software differences (especially those background services) can lead to timing differences and therefore a situation where it's just not repeatable.

Heck, if those threads have dependencies on external resources (like DB calls) the network latency differences between production and your test box might ensure that you can never duplicate it.

Shy of having a debugger on the server (bad bad idea), the best thing you can do is a visual analysis of the code, fix the parts you think need to be fixed, test it (as well as you can) then release and watch it in production.

like image 39
NotMe Avatar answered Sep 19 '22 16:09

NotMe