Thread Local Storage TLS)
In. netProgramStatic variables are globally visible (the entire application domain) data. A common static variable is visible and accessible to all threads in the application domain.
TLSIt refers to a structure in the online environment block used to store exclusive data in the thread. The thread in the process cannot access the TLS of another user.This ensures TLSData in the thread is shared globally, but invisible outside the thread.
Using system; using system. collections. generic; using system. LINQ; using system. text; using system. threading; namespace multithreadtest {class program {static void main (string [] ARGs) {for (INT I = 0; I <5; I ++) {thread = new thread (testtls. task); thread. start ();} console. read () ;}} class testtls {static localdatastoreslot localslot = thread. allocatedataslot (); public static Void task () {thread. setdata (localslot, thread. currentthread. managedthreadid); console. writeline ("thread {0}, data: {1}", thread. currentthread. managedthreadid. tostring (), thread. getdata (localslot); thread. sleep (1, 1000); console. writeline ("thread {0}, data: {1}", thread. currentthread. managedthreadid. tostring (), thread. getdata (localslot ));}}}
Output:
You can also use threadstaticattributeFeatures implement similar functions.
Using system; using system. collections. generic; using system. LINQ; using system. text; using system. threading; namespace multithreadtest {class program {static void main (string [] ARGs) {for (INT I = 0; I <5; I ++) {thread = new thread (threadstatic. task); thread. start ();} console. read () ;}} class threadstatic {[threadstatic] Static int mthreadid = 0; static int mgid = 0; public static Void task () {mthreadid = thread. currentthread. managedthreadid; mgid = thread. currentthread. managedthreadid; console. writeline ("[thread: {0}], mthreadid: {1}, mgid: {2}", thread. currentthread. managedthreadid. tostring (), mthreadid, mgid); thread. sleep (1, 1000); console. writeline ("[thread: {0}], mthreadid: {1}, mgid: {2}", thread. currentthread. managedthreadid. tostring (), mthreadid, mgid );}}}
Output: