
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Providing Thread-Safe Access to Class Members
|
1015
Thread newStaticFieldThread =
new Thread(ThreadStaticField.DisplayStaticFieldValue);
newStaticFieldThread.Start( );
ThreadStaticField.DisplayStaticFieldValue( );
}
This code now displays similar output to the following:
10 contains static field value of: Initialized string
9 contains static field value of:
The current thread does not access the bar field first and therefore does not initialize
it. However, when the new thread accesses it first, it does initialize it.
Note that adding a static constructor to initialize the static field marked with this
attribute will still follow the same behavior. Static constructors are executed only one
time per application domain.
See Also
See the “ThreadStaticAttribute Attribute” and “Static Modifier (C#)” topics in the
MSDN documentation.
18.2 Providing Thread-Safe Access to Class Members
Problem
You need to provide thread-safe access through accessor functions to an internal
member variable.
The following
NoSafeMemberAccess class shows three methods: ReadNumericField,
IncrementNumericField, and ModifyNumericField. While all of these methods access
the internal
numericField member, the access is currently not safe for multithreaded
access:
public static class NoSafeMemberAccess
{
private static int numericField ...