Making static variables thread safe RRS feed

  • Question

  • Hi,

    I have an application which has arround 50 static variables. what is the best way to make them thread safe because we are planning to run the application on multiple threads. Is using ThreadStatic attribute to all the variables a right approach??


    • Edited by M_RT Sunday, December 2, 2018 5:07 PM
    Sunday, December 2, 2018 4:44 PM


  • According to documentation, the variables marked with [ThreadStatic] become unique for each thread and are not shared between threads. Therefore, this attribute does not make shared static variables thread-safe.

    But if you do not intent to share your variables, just want to have separate data in each thread, then [ThreadStatic] is suitable.

    However note that an initialisation like ‘[ThreadStatic] static int x = 1234’  only happens in one of the threads. In other threads x will be zero. You have to initialise the variables in each thread.

    But if you want to share the variables (access from multiple threads), documentation also says that some kinds of static variables are already thread-safe for atomic read and write operations, such as bool, byte, int (and also long in 64-bit applications). However, for other operations, such as “++”, you have to use Interlocked.Increment.

    In case of objects, reading and writing of static variables (e.g. ‘static string x’) is atomic. However, the object itself (its properties and functions) is thread-safe only if designed and confirmed by documentation. For example, the string is described as thread-safe. Therefore you can use ‘x.Length’ in several threads. But if you have a ‘static List<int> x’, it is not safe to insert and read from multiple threads. You have to use locking or other collections, such as BlockingCollection<int>.

    Your own classes should be specially designed for multiple thread usage.

    Show some details about your variables and intentions.

    • Edited by Viorel_MVP Sunday, December 2, 2018 6:51 PM
    • Marked as answer by M_RT Monday, December 3, 2018 5:23 AM
    Sunday, December 2, 2018 6:42 PM