4.12. Synchronize Access to a Shared Data Value

Problem

You need to ensure operations on a numeric data value are executed atomically so that multiple threads accessing the value do not cause errors or corruption.

Solution

Use the Shared members of the System.Threading.Interlocked class.

How It Works

The Interlocked class contains several Shared methods that perform some simple arithmetic and comparison operations on a variety of data types and ensure the operations are carried out atomically. Table 4-3 summarizes the methods and the data types on which they can be used. Note that the methods use the ByRef keyword on their arguments to allow the method to update the value of the actual value type variable passed in. If an operation (such as ...

Get Visual Basic 2008 Recipes: A Problem-Solution Approach now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.