
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Preventing Silent Thread Termination
|
1021
Class 1 Thread 1
Calls
ModifyNumericField with 10
Class 2 Thread 2
Calls
ModifyNumericField with 15
Class 1 Thread 1
Calls
ReadNumericField and gets 15, not 10
Class 2 Thread 2
Calls
ReadNumericField and gets 15, which it expected
In order to solve this problem of synchronizing reads and writes, the calling class
needs to manage the interaction. The external class can accomplish this by using the
Monitor class to establish a lock on the exposed synchronization object SyncRoot
from MonitorMethodAccess, as shown here:
int num = 0;
if(Monitor.TryEnter(MonitorMethodAccess.SyncRoot,250))
{
MonitorMethodAccess.ModifyNumericField(10);
num = MonitorMethodAccess.ReadNumericField( );
Monitor.Exit(MonitorMethodAccess.SyncRoot);
}
Console.WriteLine(num);
See Also
See the “Lock Statement,” “Thread Class,” and “Monitor Class” topics in the MSDN
documentation; see the “Safe Thread Synchronization” article in the January 2003
issue of MSDN Magazine.
18.3 Preventing Silent Thread Termination
Problem
An exception thrown in a spawned worker thread will cause this thread to be silently
terminated if the exception is unhandled. You need to make sure all exceptions are
handled in all threads. If an exception happens in this new thread, you want to han-
dle it and be notified of ...