Book Image

Learning .NET High-performance Programming

By : Antonio Esposito
Book Image

Learning .NET High-performance Programming

By: Antonio Esposito

Overview of this book

Table of Contents (16 chapters)
Learning .NET High-performance Programming
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Multithreading synchronization


When dealing with multiple threads, data access in fields and properties must be synchronized, otherwise inconsistent data states may occur. Although CLR guarantees low-level data consistency by always performing a read/write operation, such as an atomic operation against any field or variable, when multiple threads use multiple variables, it may happen that during the write operation of a thread, another thread could also write the same values, creating an inconsistent state of the whole application.

First, let's take care of field initialization when dealing with multithreading. Here is an interesting example:

// a static variable without any thread-access optimization
public static int simpleValue = 10;

// a static variable with a value per thread instead per the whole process
[ThreadStatic]
public static int staticValue = 10;

//a thread-instantiated value
public static ThreadLocal<int> threadLocalizedValue = new ThreadLocal<int>(() => 10...