Given the following stack trace:
MESSAGE: Value cannot be null.Parameter name: key
SOURCE: mscorlib
TARGETSITE:
Threading might well be the cause, but it was a red herring in our case. You can also seem to have this problem if you have a Release build where a function was inlined. Consider this repro:
class Program
{
static string someKey = null;
static void Main(string[] args)
{
try
{
object thing;
if (SomeSeeminglyUnrelatedFunction(someKey, out thing)) Console.WriteLine("Found");
things.TryGetValue(someKey, out thing);
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace.ToString());
throw;
}
Console.ReadKey();
}
private static Dictionary stuff = new Dictionary();
private static Dictionary things = new Dictionary();
private static bool SomeSeeminglyUnrelatedFunction(string key, out object item)
{
return stuff.TryGetValue(key, out item);
}
}
On my machine this gives the following Debug build stack trace:
at System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
at System.Collections.Generic.Dictionary`2.TryGetValue(TKey key, TValue& value)
at MyApp.Program.SomeSeeminglyUnrelatedFunction(String key, Object& item)
at MyApp.Program.Main(String[] args)
But, it gives this stack trace in Release build:
at System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
at System.Collections.Generic.Dictionary`2.TryGetValue(TKey key, TValue& value)
at MyApp.Program.Main(String[] args)
You'd be tempted to think with that last stack trace that it has to be things.TryGetValue that causes the exception, when in fact it was the SomeSeeminglyUnrelatedFunction function that got inlined in Main.
So if you land here, please consider if you have a similar issue. (I realize this may not be a straight up answer to OP's question, but wanted to share nonetheless as it might help a future visitor.)