Thread Local Storage For C# Class Library

后端 未结 4 1697
不思量自难忘°
不思量自难忘° 2021-01-04 08:06

I have a very old but very large library which I am considering converting to a C# class library. The existing library uses a lot of global variables stored in the TLS. C# h

4条回答
  •  有刺的猬
    2021-01-04 08:18

    There are the ThreadLocal class (introduced in 4.0) and the ThreadStaticAttribute.

    The ThreadStaticAttribute can be used only on static fields. The ThreadLocal class can be used on "normal" fields but it is slower.

    Be aware that if you don't control the thread you are on (for example you are a page of ASP.NET and you start on a "random" pre-used thread, or you are a thread of a ThreadPool), then your "thread-static" (in general, not the attribute) variables will be pre-initialized with the old values of the previous thread. (see for example A tale of two techniques: The [ThreadStatic] Attribute and System.Web.HttpContext.Current.Items)

    I was forgetting, there is the Thread.AllocateDataSlot that has similar "objectives" than the others.

提交回复
热议问题