P
P
polyakovyevgeniy2016-11-03 15:57:57
.NET
polyakovyevgeniy, 2016-11-03 15:57:57

How to trick the C# optimizer?

There is this code:

public IEnumerable<NodeBase> GetServerSpace(IsoConnectionParameters connectionParameters)
        {
            _isWait = true;
            var worker = new Scsm_MMS_Worker(new Env());
            Task.Factory.StartNew(() =>
            {
                worker.Start(connectionParameters, ReturnIedTree, string.Empty);
                while (_isWait)
                {
                    
                }
            }).Wait();

            worker.Stop();
            return _node;
        }

        private bool _isWait;

In Debug mode, this code works fine and return is called. But in release mode, the while loop never terminates, and runs indefinitely. But if you add Trace.WriteLine("") to the body of the while loop, then the code also works well.
public IEnumerable<NodeBase> GetServerSpace(IsoConnectionParameters connectionParameters)
        {
            _isWait = true;
            var worker = new Scsm_MMS_Worker(new Env());
            Task.Factory.StartNew(() =>
            {
                worker.Start(connectionParameters, ReturnIedTree, string.Empty);
                while (_isWait)
                {
                    Trace.WriteLine("");
                }
            }).Wait();

            worker.Stop();
            return _node;
        }

Why does the optimizer do this, and how can you still execute the code normally without using Trace.WriteLine in the loop body?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
P
Peter, 2016-11-03
@polyakovyevgeniy

private volatile bool _isWait;

M
Maxim Grekhov, 2016-11-12
@Sterk

It is clear that the problem can be solved differently, but it seems to me that you should look towards CancellationTokenSource.

M
Michael, 2016-11-22
@Sing303

The question is why are you doing this when there are ResetEvents

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question