Proper way to have an endless worker thread?

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

    I've implemented a background-task queue without using any kind of while loop, or pulsing, or waiting, or, indeed, touching Thread objects at all. And it seems to work. (By which I mean it's been in production environments handling thousands of tasks a day for the last 18 months without any unexpected behavior.) It's a class with two significant properties, a Queue and a BackgroundWorker. There are three significant methods, abbreviated here:

    private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
    {
       if (TaskQueue.Count > 0)
       {
          TaskQueue[0].Execute();
       }
    }
    
    private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        Task t = TaskQueue[0];
    
        lock (TaskQueue)
        {
            TaskQueue.Remove(t);
        }
        if (TaskQueue.Count > 0 && !BackgroundWorker.IsBusy)
        {
            BackgroundWorker.RunWorkerAsync();
        }
    }
    
    public void Enqueue(Task t)
    {
       lock (TaskQueue)
       {
          TaskQueue.Add(t);
       }
       if (!BackgroundWorker.IsBusy)
       {
          BackgroundWorker.RunWorkerAsync();
       }
    }
    

    It's not that there's no waiting and pulsing. But that all happens inside the BackgroundWorker. This just wakes up whenever a task is dropped in the queue, runs until the queue is empty, and then goes back to sleep.

    I am far from an expert on threading. Is there a reason to mess around with System.Threading for a problem like this if using a BackgroundWorker will do?

提交回复
热议问题