>
>
>
V3032. Waiting on this expression is un…


V3032. Waiting on this expression is unreliable, as compiler may optimize some of the variables. Use volatile variable(s) or synchronization primitives to avoid this.

The analyzer has detected a loop that may turn into an infinite one due to compiler-driven optimization. Such loops are usually used when the program is waiting for an external event.

Consider the following example:

private int _a;
public void Foo()
{
    var task = new Task(Bar);
    task.Start();
    Thread.Sleep(10000);
    _a = 0;
    task.Wait();
}

public void Bar()
{
    _a = 1;
    while (_a == 1);        
}

If this code is compiled and executed in Debug configuration, the program will terminate correctly. But when compiled in Release mode, it will hang at the while loop. The reason is that the compiler will "cache" the value referred to by the '_a' variable.

This difference between Debug and Release versions may lead to complicated and hard-to-detect bugs, which can be fixed in a number of ways. For example, if the variable in question is really used to control the logic of a multithreaded program, special synchronization means such as mutexes or semaphores should be used instead. Another way is to add modifier 'volatile' to the variable definition:

private volatile int _a;
...

Note that these means alone do not secure the sample code completely since Bar() is not guaranteed to start executing before the '_a' variable is assigned 0. We discussed this example only to demonstrate a potentially dangerous situation related to compiler optimizations. To make that code completely safe, additional synchronization is required before the _a = 0 expression to ensure that the _a = 1 expression has been executed.

This diagnostic is classified as:

You can look at examples of errors detected by the V3032 diagnostic.