18.1. Creating Per-Thread Static Fields
Problem
Static fields, by default, are shared between threads within an application domain. You need to allow each thread to have its own nonshared copy of a static field, so that this static field can be updated on a per-thread basis.
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( );
}This code displays output that resembles the ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access