Skip to Main Content
C# in a Nutshell, Second Edition
book

C# in a Nutshell, Second Edition

by Peter Drayton, Ben Albahari, Ted Neward
August 2003
Intermediate to advanced content levelIntermediate to advanced
928 pages
32h 1m
English
O'Reilly Media, Inc.
Content preview from C# in a Nutshell, Second Edition

Name

Interlocked

Synopsis

The static members of this class provide thread safety for common built-in arithmetic operations, such as increasing and decreasing a variable by one, and exchanging variables.

If two threads increment the same variable, one thread could be interrupted after both have retrieved the initial value of the variable. If this happens, then both operations store the same value, meaning that the variable has been incremented once instead of twice. The Interlocked methods protect against this kind of error. Increment( ) and Decrement( ) increase and decrease a variable by one, respectively, and Exchange( ) switches two variables. CompareExchange( ) compares the first two variables and, if true, assigns the third value to the first variable.

public sealed class Interlocked {
// Public Static Methods
   public static int CompareExchange(ref int location1, int value, int comparand);
   public static object CompareExchange(ref object location1, object value, object comparand);
   public static float CompareExchange(ref float location1, float value, float comparand);
   public static int Decrement(ref int location);
   public static long Decrement(ref long location);
   public static int Exchange(ref int location1, int value);
   public static object Exchange(ref object location1, object value);
   public static float Exchange(ref float location1, float value);
   public static int Increment(ref int location);
   public static long Increment(ref long location);
}
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# in a Nutshell

C# in a Nutshell

Ben Albahari, Ted Neward, Peter Drayton
C# 7.0 in a Nutshell

C# 7.0 in a Nutshell

Joseph Albahari, Ben Albahari
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
C# Cookbook

C# Cookbook

Stephen Teilhet, Jay Hilyard

Publisher Resources

ISBN: 0596005261Catalog PageErrata