"is it safe to use a boolean flag to stop a thread from running in c#" Code Answer

5

you better mark it volatile though:

the volatile keyword indicates that a field might be modified by multiple concurrently executing threads. fields that are declared volatile are not subject to compiler optimizations that assume access by a single thread. this ensures that the most up-to-date value is present in the field at all times.

but i would change your loop:

    startsignal.waitone();
    while(running)
    {
        //... some code
        startsignal.waitone();
    }

as it is in your post the 'some code' might execute when the thread is stopped (ie. when stop is called) which is unexpected and may be even incorrect.

By Baversjo on January 13 2022

Answers related to “is it safe to use a boolean flag to stop a thread from running in c#”

Only authorized users can answer the Search term. Please sign in first, or register a free account.