S
S
Sergey2022-04-15 23:19:50
C++ / C#
Sergey, 2022-04-15 23:19:50

Is it correct to stop a thread with a flag?

I have a boolean variable flag that is initialized to false
I set it to true and use Task.Run to run a task that has a while loop that runs while flag == true
If I want to stop the task I can simply set flag to false. This is convenient because the task is guaranteed not to stop in the middle of the while. The question is, if the entry to the flag variable gets at the time of reading from it, then how will the program behave in this case? And if this can lead to a crash of the program, then what is the best object to implement this functionality?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
forced, 2022-04-16
@forced

CancellationToken
IsCancellationRequired

V
Vasily Bannikov, 2022-04-16
@vabka

In principle, nothing very terrible will happen, but it’s better to solve this problem through CancellationToken and CancellationTokenSource)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question