threadstatic

Initializing ThreadStatic field still causes NullReferenceException

我怕爱的太早我们不能终老 提交于 2019-11-27 11:57:44
问题 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

How does the ThreadStatic attribute work?

半城伤御伤魂 提交于 2019-11-27 05:02:37
问题 How does [ThreadStatic] attribute work? I assumed that the compiler would emit some IL to stuff/retrieve the value in the TLS, but looking at a disassembly it doesn't seem to do it at that level. As a follow up, what happens if you put it on a non-static member? We had a developer make that mistake and the compiler doesn't even proffer up a warning. Update Second question answered here: ThreadStatic Modified with Static C# 回答1: The implementation semantics of thread static are below the IL

ThreadStatic v.s. ThreadLocal<T>: is generic better than attribute?

一曲冷凌霜 提交于 2019-11-27 03:36:58
[ThreadStatic] is defined using attribute while ThreadLocal<T> uses generic. Why different design solutions were chosen? What are the advantages and disadvantages of using generic over attributes in this case? Jim Mischel Something the blog post noted in the comments doesn't make explicit, but I find to be very important, is that [ThreadStatic] doesn't automatically initialize things for every thread. For example, say you have this: [ThreadStatic] private static int Foo = 42; The first thread that uses this will see Foo initialized to 42 . But subsequent threads will not. The initializer works

ThreadStaticAttribute in ASP.NET

孤街浪徒 提交于 2019-11-26 18:21:00
问题 I have a component that needs to store static values fore each thread. It's a general component that can be used in many scenarios and not only in ASP.NET. I was thinking to use the [ThreadStatic] attribute to achieve my goal. Supposing that it would also work fine in ASP.NET scenarios, because i was assuming that every Request is called in a own thread. After some research i found this Blog Post from Scott Hanselman saying to be careful when using [ThreadStatic] in ASP.NET. However most of