
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
1064
|
Chapter 18: Threading and Synchronization
If there has not been much threading or assembly language in your past, you might
wonder what the big deal is and why you need these atomic functions at all. The
basic reason is that the line of code written in C# ultimately has to be translated
down to a machine instruction and along the way the one line of code written in C#
can turn into multiple instructions for the machine to execute. If the machine has to
execute multiple instructions to perform a task and the operating system allows for
preemption, it is possible that these instructions may not be executed as a block.
They could be interrupted by other code that modifies the value being changed by
the original line of C# code in the middle of the C# code being executed. As you can
imagine, this could lead to some pretty spectacular errors, or it might just round off
the lottery number that keeps a certain C# programmer from winning the big one.
Threading is a powerful tool, but like most “power” tools, you have to understand
its operation to use it effectively and safely. Threading bugs are notorious for being
some of the most difficult to debug, as the runtime behavior is not constant. Trying
to reproduce them can be a nightmare. Recognizing that working in a multithreaded
environment ...