Quick question regarding ThreadStatic
and ThreadLocal
in C#, specifically .Net Core 3.1.6..
I would rather not post the exact example but it's very similar to this:
[ThreadStatic]
static readonly Object LocalObject = new Object();
I then access said object from multiple different threads using ParrallelEnumerable
or Tasks.Parallel
and I run into a very interesting exception which unfortunately crashed the runtime...
The intention of my code is that every Thread
which accesses LocalObject
will have it's own instance as shown
Are there any known issues around ThreadLocal
/ ThreadStatic
in .Net Core 3.1.6 and where can I read about them?
If there is nothing indicated as changed or different for 3.1.6 are there changes in 5.0 related to the same attributes? If none of those then has .Net core changed the behavior of these constructs from their Full Framework implementation?
Thank you for your time!
Based on the documentation you provided in the link, the problems is that when you access the variable, the value is null because:
So, if you try to do something with the variable, expecting the variable to have an
Object
instance, it will throw an exception which if not handled will make the application fail.Edit - 7/21/2020
After some tests, I finally came to a conclusion: The field cannot be
readonly
due to initialization issues, that is, the field would be initialized only for the first thread, inline or in thestatic
constructor. Any subsequentthread
will only get anull
value.The closest I was able to get is as follows: