Skip to Main Content
C# Cookbook, 2nd Edition
book

C# Cookbook, 2nd Edition

by Jay Hilyard, Stephen Teilhet
January 2006
Intermediate to advanced content levelIntermediate to advanced
1184 pages
43h 23m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook, 2nd Edition
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( );
}
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, ...
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.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Stephen Teilhet, Jay Hilyard
C# Cookbook

C# Cookbook

Joe Mayo
Head First C#, 4th Edition

Head First C#, 4th Edition

Andrew Stellman, Jennifer Greene

Publisher Resources

ISBN: 0596100639Supplemental ContentCatalog PageErrata