Thankfully, the System.Threading namespace offers
the Interlocked class to perform these swap operations atomically, and best of all, the methods
are guaranteed never to throw exceptions. The Interlocked class provides a generic
overload of all of the useful methods, making them very efficient. The generic Interlocked
methods come with a constraint that they only work with reference types.
The bottom line is, you should do everything that can possibly throw an exception before
modifying the state of the object being operated on. Once you know you??™re past the point of
possibly causing any exceptions, commit the changes using operations that are guaranteed not
to throw exceptions. If you??™re tasked to create a robust, real-world system where many people
rely on the integrity of the system, the importance of this idiom cannot be stressed enough.
Constrained Execution Regions
The example in the previous section demonstrates some of the level of paranoia you must
endure in order to write bulletproof, exception-neutral code. We were so paranoid that a stack
overflow would occur that we allocated the extra space needed by ListSwap() before we called
the method. You would think that would take care of all of the issues. Unfortunately, you??™d be
wrong.
Pages:
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254