Friday, December 10, 2010

Sometimes when working with C# you discover some hidden gems. Some of them very useful, other ones a little bit harder to find a good way to benefit from their functionality. One of those hidden gems that I discovered some time ago is the volatile keyword.

The volatile keyword indicates that a field might be modified by multiple threads that are executing at the same time. Fields that are declared volatile are not subject to compiler optimizations that assume access by a single thread. This ensures that the most up-to-date value is present in the field at all times.

The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock statement to serialize access.

The following example demonstrates how an auxiliary or worker thread can be created and used to perform processing in parallel with that of the primary thread.

1: using System;

2: using System.Threading;

3:

4: publicclass Worker

5: {

6: // This method is called when the thread is started.

7: publicvoid DoWork()

8: {

9: while (!_shouldStop)

10: {

11: Console.WriteLine("Worker thread: working...");

12: }

13: Console.WriteLine("Worker thread: terminating gracefully.");

14: }

15: publicvoid RequestStop()

16: {

17: _shouldStop = true;

18: }

19: // Keyword volatile is used as a hint to the compiler that this data

20: // member is accessed by multiple threads.

21: privatevolatilebool _shouldStop;

22: }

23:

24: publicclass WorkerThreadExample

25: {

26: staticvoid Main()

27: {

28: // Create the worker thread object. This does not start the thread.