QUESTION: Why does not this program quit when compiled in Release mode?

The following works as expected when building in Debug – the execution is done after three seconds. But, for some reason, it fails when in Release.

class Program
{
    static void Main(string[] args)
    {
        var w = new Worker();
        while (!w.IsDone);
        Console.WriteLine("The work is done.");
    }
}

class Worker
{
    public bool IsDone;

    public Worker()
    {
        var thread = new Thread(Job);
        thread.Start();
    }

    private void Job()
    {
        Thread.Sleep(3000);
        IsDone = true;
    }
}

Could you explain what is happening? How could you fix it?

Tomorrow, I will share the answer.

Compartilhe este insight:

3 respostas

  1. This was a nice lesson. I’m still quite new to multithreading, so I had to learn what was going on. Ended up diving in C# documentation to know more. Below is the answer, so if you haven’t done it, SPOILER ALERT!

    This happens because the compiler assumes your application is single-threaded, and optimizes it accordingly. Therefore, when Worker is created, it only sees the need to check for the variable’s value one single time, since it isn’t being changed on that thread. Simply adding the keyword “volatile” on the variable’s declaration will tell the compiler to keep watching for changes.

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *

Elemar Júnior

Sou fundador e CEO da EximiaCo e atuo como tech trusted advisor ajudando diversas empresas a gerar mais resultados através da tecnologia.

Elemar Júnior

Sou fundador e CEO da EximiaCo e atuo como tech trusted advisor ajudando diversas empresas a gerar mais resultados através da tecnologia.

Mais insights para o seu negócio

Veja mais alguns estudos e reflexões que podem gerar alguns insights para o seu negócio:

In this post, I would like to explain a basic but confusing concept of CUDA programming: Thread Hierarchies. It will...
Neste post, vou compartilhar como dar os primeiros passos com OpenCV, rapidamente, usando Visual Studio 2017 e VcPkg. O que...
Inspecting the code repository of a client, I found something like this: var customer = new { Id = default(int),...
Algumas vezes, desejamos escrever funções que não retornam, necessariamente, um resultado. Nesses casos, podemos usar o contêiner std::optional. Trata-se de...
Ano passado, Mario Fusco escreveu uma série de posts questionando a forma como programadores Java estão implementando os padrões de projeto definidos...
Neste post, compartilho mais algumas ideias que tenho adotado, com êxito, em meus projetos envolvendo Microsserviços e que podem ajudar...
× Precisa de ajuda?