2 years ago

#29843

test-img

EldHasp

How to remove unnecessary caching of a variable?

A simple example.

A class with a method creating a task and a flag for exiting the loop:

using System.Threading.Tasks;

namespace Examp
{
    public class CancelFlag
    {
        public bool Flag;

        public Task<int> Start()
        {
            Flag = false;
            Task.Delay(100).ContinueWith(_ => Flag = true);
            return Task.Run(PrivateStart);
        }
        private int PrivateStart()
        {
            int sum = 0;
            while (!Flag)
                sum++;
            return sum;
        }
    }
}

Its use:

    Examp.CancelFlag cancelFlag = new Examp.CancelFlag();

    var task = cancelFlag.Start();
    task.Wait();
    Console.WriteLine(task.Result);

When compiled in Debud mode, it works as expected.

But if you compile in Release, then the Flag is cached.
Because of this, the new value of the flag is not read and the loop does not exit.

How can you explicitly indicate here that in each check you need to read the new value of the Flag field?

c#

multithreading

field

volatile

0 Answers

Your Answer

Accepted video resources