vendredi 2 août 2019

Is it good practice / thread safe to negate the value of a bool directly after if-checking it in C#?

I asked myself whether it is possible to write an if statement that checks for a bool variable and then directly changes its value before entering the statement's body.

So, instead of writing

if (getNextImage)
{
    getNextImage = false;
    // do some more stuff                     
}

I tried this

if (getNextImage ? !(getNextImage = false) : false) 
{
    // do some more stuff 
}

which worked.

The reason for this is that the code runs in several threads at the same time and I wanted to be sure that the if block is just executed once in the first thread coming to that line in the code.

My question is: Is this approach good practice and will it work the way I intended it to? If not, are there other approaches besides a lock?

Aucun commentaire:

Enregistrer un commentaire