Initializing ThreadStatic field still causes NullReferenceException

C#RandomThread SafetyThreadstatic

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

Initializing ThreadStatic fields is a little tricky. In particular there is this caveat:

> Do not specify initial values for fields marked with > ThreadStaticAttribute, because such initialization occurs only once, > when the class constructor executes, and therefore affects only one > thread.

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)

[ThreadStatic]
private static string Foo = "the foo string";

> The ThreadStatic is initialized in the static constructor - which only > executes once. So only the very first thread is assigned "the foo > string" when the static constructor executes. When accessed in all > subsequent threads, Foo is left at the uninitalized null value. > > The best way to work around this is to use a property to access the > Foo prop.

[ThreadStatic]
private static string _foo;

public static string Foo {
   get {
     if (_foo == null) {
         _foo = "the foo string";
     }
     return _foo;
   }
}

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: https://stackoverflow.com/questions/11507881/threadstatic-and-synchronization

Solution 2 - C#

Previous answer is correct as to the reason for the issue.

if you can use .NET 4 or higher, use ThreadLocal instead as is built with an initializer.

See https://stackoverflow.com/questions/18333885/threadstatic-v-s-threadlocalt-is-generic-better-than-attribute

Then you don't need the accessor overload or null check on every read.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTarecView Question on Stackoverflow
Solution 1 - C#hatchet - done with SOverflowView Answer on Stackoverflow
Solution 2 - C#David BurgView Answer on Stackoverflow