Is Thread.CurrentThread static ? RRS feed

  • Question

  • I've just started to learn multithreading,  and I don't understand Thread.CurrentThread.
    According to the MS documentation, it is a static property of the Thread class, so how can it be different for each running thread ?
    Thursday, October 10, 2019 11:34 AM


All replies

  • As documentation says it is currently running thread. Property getter actually calls native method to get current thread.

    Static property does not mean that its value would be same for everyone. Consider for example DateTime.Now that changes all the time because time changes and will not return same value all the time, not even in same thread. Static property values can change based on execution context or environment or just some other factor.

    Thursday, October 10, 2019 12:06 PM
  • It is through a concept called "thread local storage".  Certain variables can be marked as TLS.  Each thread gets its own private TLS block, so any variables marked as TLS will be unique to the tread.

    You can declare your own thread local data using ThreadLocal<T>

    Tim Roberts | Driver MVP Emeritus | Providenza &amp; Boekelheide, Inc.

    Thursday, October 10, 2019 6:12 PM