
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Creating Per-Thread Static Fields
|
1013
Solution
Use ThreadStaticAttribute to mark any static fields as not shareable between
threads:
using System;
using System.Threading;
public class Foo
{
[ThreadStaticAttribute( )]
public static string bar = "Initialized string";
}
Discussion
By default, static fields are shared between all threads that access these fields in the
same application domain. To see this, you’ll create a class with a static field called
bar and a static method to access and display the value contained in this field:
using System;
using System.Threading;
public class ThreadStaticField
{
public static string bar = "Initialized string";
public static void DisplayStaticFieldValue( )
{
string msg =
string.Format("{0} contains static field value of: {1}",
Thread.CurrentThread.GetHashCode( ),
ThreadStaticField.bar);
Console.WriteLine(msg);
}
}
Next, create a test method that accesses this static field both on the current thread
and on a newly spawned thread:
public static void TestStaticField( )
{
ThreadStaticField.DisplayStaticFieldValue( );
Thread newStaticFieldThread =
new Thread(ThreadStaticField.DisplayStaticFieldValue);
newStaticFieldThread.Start( );
ThreadStaticField.DisplayStaticFieldValue( );
}