Proper way to have an endless worker thread?

前端 未结 6 1493
慢半拍i
慢半拍i 2021-01-31 00:36

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\"

6条回答
  •  攒了一身酷
    2021-01-31 01:31

    In most cases, I've done this quite similar to how you've set up -- but not in the same language. I had the advantage of working with a data structure (in Python) which will block the thread until an item is put into the queue, negating the need for the sleep call.

    If .NET provides a class like that, I'd look into using it. A thread blocking is much better than a thread spinning on sleep calls.

    The job you can pass could be as simple as a "null"; if the code receives a null, it knows it's time to break out of the while and go home.

提交回复
热议问题