Proper way to have an endless worker thread?

前端 未结 6 1488
慢半拍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:32

    Grab the Parallel Framework. It has a BlockingCollection which you can use as a job queue. How you'd use it is:

    1. Create the BlockingCollection that will hold your tasks/jobs.
    2. Create some Threads which have a never-ending loop (while(true){ // get job off the queue)
    3. Set the threads going
    4. Add jobs to the collection when they come available

    The threads will be blocked until an item appears in the collection. Whoever's turn it is will get it (depends on the CPU). I'm using this now and it works great.

    It also has the advantage of relying on MS to write that particularly nasty bit of code where multiple threads access the same resource. And whenever you can get somebody else to write that you should go for it. Assuming, of course, they have more technical/testing resources and combined experience than you.

提交回复
热议问题