How to keep a thread alive and waiting for a boolean?

Viewed 39

I have a thread in a unity(c#) application and this thread's duty is to wait for a boolean to become true and then save something and die. since I mentioned unity, I want to also say that the class that contains my codes is not a MonoBehaviour hence I do not have the Update() to repeatedly check for the boolean.

I tried to make a MonoBehaviour class and use its Update() to do the job but the properties of the Non-MonoBehaviour class (the main class) are all private and can not be accessed from other classes.

The simplest and cleanest way I found to do that is, to have a while loop in the thread to keep it alive. Since the while loop was drawing a lot of CPU power I added a Thread.Sleep(500) inside of it which apparently fixed the problem according to the task manager.

My question is, Is having a while loop inside of a thread in order to keep it alive a good practice? and also about the Thread.Sleep(500), is it OK to slow down a loop using Thread.Sleep(500)

Here is my code:

 Thread thread = new Thread(() =>
    {
        while (true)
        {

            Thread.Sleep(500);


            if (!_isRunning)
            {
                break;
            }

            if (RequiredSegments < minSegments)
            {
                continue;
            }

            IsDone = _object.SaveSegments();

            if (IsDone)
            {
                FetchValues();
            }

            Terminate();

            break;
        }
    });

    thread.Start();

Please feel free to give me any suggestion,

Regards

0 Answers
Related