Thread Local Storage

Microsoft Silverlight will reach end of support after October 2021. Learn more.

You can use managed thread local storage (TLS) to store data that is unique to a thread and application domain. The .NET Framework provides thread-relative static fields for this purpose.

NoteNote:

A Silverlight-based application has only one application domain; therefore, TLS is effectively unique to a thread.

To store a piece of data that is always unique to a thread, store the data in a static field (a Shared field in Visual Basic) and apply the ThreadStaticAttribute attribute to the static field. Use the field as you would use any other static field. The data in the field is unique to each thread that uses it.

Be aware that any class constructor code will run on the first thread in the first context that accesses the field. In all other threads or contexts in the same application domain, the fields will be initialized to null (Nothing in Visual Basic) if they are reference types, or to their default values if they are value types. Therefore, you should not rely on class constructors to initialize thread-relative static fields. Instead, avoid initializing thread-relative static fields and assume that they are initialized to null (Nothing) or to their default values.