Proper way to have an endless worker thread?

Posted by Neil N on Stack Overflow See other posts from Stack Overflow or by Neil N
Published on 2009-10-14T15:21:56Z Indexed on 2010/04/07 16:53 UTC
Read the original article Hit count: 250

I have an object that requires a lot of initialization (1-2 seconds on a beefy machine). Though once it is initialized it only takes about 20 miliseconds to do a typical "job"

In order to prevent it from being re-initialized every time an app wants to use it (which could be 50 times a second or not at all for minutes in typical usage), I decided to give it a job que, and have it run on its own thread, checking to see if there is any work for it in the que. However I'm not entirely sure how to make a thread that runs indefinetly with or without work.

Here's what I have so far, any critique is welcomed

    private void DoWork()
    {
        while (true)
        {
            if (JobQue.Count > 0)
            {
                // do work on JobQue.Pop()
            }
            else
            {
                System.Threading.Thread.Sleep(50);
            }
        }
    }

After thought: I was thinking I may need to kill this thread gracefully insead of letting it run forever, so I think I will add a Job type that tells the thread to end. Any thoughts on how to end a thread like this also appreciated.

© Stack Overflow or respective owner

Related posts about c#

Related posts about multithreading