Csharp/CSharp Tutorial/Thread/Static Thread Field

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Static Thread field

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

Thread Static field

using System;
using System.Threading;
public class Task {
 
  [ThreadStatic] 
  static int id = 10;
  public string  threadName;
  
  public void Run( string ThreadName ) {
    this.threadName = ThreadName;
    Thread T = new Thread( new ThreadStart( process ) );
    T.Start( );
  }
  public void process( ) {
    Console.WriteLine( "Thread {0} is running", threadName );
    for(int i = 0; i < 10; i++ )
      Console.WriteLine("Thread {0} : id = {1}", this.threadName, id++ );
  }
}

public class MainClass {
  public static void Main( ) {
    Task t1 = new Task( );
    Task t2 = new Task( );
    t1.Run( "Worker 1" );
    t2.Run( "Worker 2" );
    
    Task t3 = new Task( );
    t3.threadName = "Main Thread";
    t3.process( );
  }
}
Thread Worker 1 is running
Thread Worker 1 : id = 0
Thread Worker 1 : id = 1
Thread Worker 1 : id = 2
Thread Worker 1 : id = 3
Thread Worker 1 : id = 4
Thread Worker 1 : id = 5
Thread Worker 1 : id = 6
Thread Worker 1 : id = 7
Thread Worker 1 : id = 8
Thread Worker 1 : id = 9
Thread Worker 2 is running
Thread Worker 2 : id = 0
Thread Worker 2 : id = 1
Thread Worker 2 : id = 2
Thread Worker 2 : id = 3
Thread Worker 2 : id = 4
Thread Worker 2 : id = 5
Thread Worker 2 : id = 6
Thread Worker 2 : id = 7
Thread Worker 2 : id = 8
Thread Worker 2 : id = 9
Thread Main Thread is running
Thread Main Thread : id = 10
Thread Main Thread : id = 11
Thread Main Thread : id = 12
Thread Main Thread : id = 13
Thread Main Thread : id = 14
Thread Main Thread : id = 15
Thread Main Thread : id = 16
Thread Main Thread : id = 17
Thread Main Thread : id = 18
Thread Main Thread : id = 19