Home > Enterprise >  Can background workers run even when the foreground is in a tight loop?
Can background workers run even when the foreground is in a tight loop?

Time:11-02

I have a background worker running doing its thing. In the foreground, I have a tight while loop that only looks at a local variable to exit. The local variable is set by an event handler triggered by the background worker.

My thought was that I would need to call sleep to allow the background thread to run, but that does not appear to be the case. Why does this work?

This is a console app for test purposes, so no GUI thread.

        while (true)
        {
            //System.Threading.Thread.Sleep(50);

            /* Get out if scripts are finished. */
            if (!m_NfcScriptRunning)
                break;
        }

Regards, Lee

CodePudding user response:

My thought was that I would need to call sleep to allow the background thread to run, but that does not appear to be the case. Why does this work?

Because a BackgroundWorker is essentially a separate thread.

The local variable is set by an event handler triggered by the background worker.

Don't use ordinary variables for thread synchronization, you'd run into various issues caused by how the modern CPU's memory architecture works. Instead, use some of the available synchronization primitives. One of the advantages is that waiting for e.g. an event doesn't consume CPU cycles.

CodePudding user response:

The entire idea of a separate thread is that the code runs in parallel, so no, you don't have to use Thread.Sleep, as that will only sleep the 'foreground' thread in which you are using it.

  • Related