Nedávno jsem narazil na třídu System.ThreadStaticAttribute. Jeho funkcionalita je opravdu skvělá. Zařizuje pro každé vlákno různou hodnotu. Takový jednoduchý příklad - zkuste si pustit následující kód s a bez ThreadStatic atributu:
class AAA {
static void Start() {
System.Threading.Thread thread_1 = new System.Threading.Thread( new System.Threading.ParameterizedThreadStart( Worker ) );
System.Threading.Thread thread_2 = new System.Threading.Thread( new System.Threading.ParameterizedThreadStart( Worker ) );
thread_1.Start( "ahoj" );
thread_2.Start( "baf" );
}
static void Worker( object obj ) {
FlyWeightClass fly = FlyWeightClass.Default;
fly.SomeText = obj != null ? obj.ToString() : "( null )";
for ( int i = 0; i < 100; i++ ) {
Console.WriteLine( fly.SomeText );
System.Threading.Thread.Sleep( 100 );
}
}
}
class FlyWeightClass {
[ThreadStatic]
private static FlyWeightClass threadSingelton;
public static FlyWeightClass Default {
get {
FlyWeightClass ret = FlyWeightClass.threadSingelton;
if ( ret == null ) { FlyWeightClass.threadSingelton = ret = new FlyWeightClass(); }
return ret;
}
}
public string SomeText;
}
Důležitá poznámka je, že v takovýchto případech je potřeba vyhnout se inicializaci statické proměné v deklaraci. Taková inicializace se provede pouze jednou, a při přístupu z jiného vlákna tam pak budete mít výchozí hodnotu.