Static Thread field : Static Thread Field « Thread « C# / CSharp Tutorial






using System;
using System.Threading;

public class MyClass
{
    public MyClass() {
        Console.WriteLine( "Creating MyClass" );
    }
}

public class MyStaticThreadClass
{
    [ThreadStatic]
    public static MyClass tlsdata = new MyClass();
}

public class MainClass
{
    private static void ThreadFunc() {
        Console.WriteLine( "Thread {0} starting...", Thread.CurrentThread.GetHashCode() );
        Console.WriteLine( "tlsdata for this thread is \"{0}\"", MyStaticThreadClass.tlsdata );
        Console.WriteLine( "Thread {0} exiting", Thread.CurrentThread.GetHashCode() );
    }

    static void Main() {
        Thread thread1 = new Thread( new ThreadStart(ThreadFunc) );
        Thread thread2 = new Thread( new ThreadStart(ThreadFunc) );

        thread1.Start();
        thread2.Start();
    }
}
Thread 3 starting...
Creating MyClass
tlsdata for this thread is "MyClass"
Thread 3 exiting
Thread 4 starting...
tlsdata for this thread is ""
Thread 4 exiting








20.27.Static Thread Field
20.27.1.Static Thread field
20.27.2.Thread Static field