Proper way to have an endless worker thread?

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

    You need to lock anyway, so you can Wait and Pulse:

    while(true) {
        SomeType item;
        lock(queue) {
            while(queue.Count == 0) {
                Monitor.Wait(queue); // releases lock, waits for a Pulse,
                                     // and re-acquires the lock
            }
            item = queue.Dequeue(); // we have the lock, and there's data
        }
        // process item **outside** of the lock
    }
    

    with add like:

    lock(queue) {
        queue.Enqueue(item);
        // if the queue was empty, the worker may be waiting - wake it up
        if(queue.Count == 1) { Monitor.PulseAll(queue); }
    }
    

    You might also want to look at this question, which limits the size of the queue (blocking if it is too full).

提交回复
热议问题