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.
1016
|
Chapter 18: Threading and Synchronization
{
return (numericField);
}
}
Solution
NoSafeMemberAccess could be used in a multithreaded application, and therefore it
must be made thread-safe. Consider what would occur if multiple threads were call-
ing the
IncrementNumericField method at the same time. It is possible that two calls
could occur to
IncrementNumericField while the numericField is updated only once.
In order to protect against this, you will modify this class by creating an object that
you can lock against in critical sections of the code:
public static class SaferMemberAccess
{
private static int numericField = 1;
private static object syncObj = new object( );
public static void IncrementNumericField( )
{
lock(syncObj)
{
++numericField;
}
}
public static void ModifyNumericField(int newValue)
{
lock(syncObj)
{
numericField = newValue;
}
}
public static int ReadNumericField( )
{
lock (syncObj)
{
return (numericField);
}
}
}
Using the lock statement on the syncObj object lets you synchronize access to the
numericField member. This now makes all three methods safe for multithreaded
access.
Discussion
Marking a block of code as a critical section is done using the lock keyword. The
lock keyword should not be used on a public type or on an instance out of the
This is the Title of 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.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook

C# Cookbook

Stephen Teilhet, Jay Hilyard
Head First C#, 4th Edition

Head First C#, 4th Edition

Andrew Stellman, Jennifer Greene

Publisher Resources

ISBN: 0596100639Supplemental ContentCatalog PageErrata