I've written myself a multi-threaded random generator
public static class MyRandGen
{
private static Random GlobalRandom = new Random();
[ThreadStatic]
private static Random ThreadRandom = new Random(SeedInitializer());
private static int SeedInitializer()
{
lock (GlobalRandom) return GlobalRandom.Next();
}
public static int Next()
{
return ThreadRandom.Next();
}
}
However, it throws me a NullReferenceException on firing Next(), which I don't understand. Is that kind of initializing ThreadStatic fields forbidden somehow?
I know I could just check if the field's initialized every time, but that's not the solution I'm looking for.
Initializing ThreadStatic fields is a little tricky. In particular there is this caveat:
in the MSDN Docs. What this means is that the thread running when the class is initialized gets that initial value you've defined in the field declaration, but all other threads will have a value of null. I think this is why your code is exhibiting the undesirable behavior described in your question.
A fuller explanation is in this blog.
(a snippet from the blog)
Note that there is no need for a lock in the static property, because each thread is acting upon the
_foo
that is just for that thread. There can't be contention with other threads. This is covered in this question: ThreadStatic and Synchronization