This BackgroundWorker is currently busy and cannot run multiple tasks concurrently

前端 未结 4 944
野趣味
野趣味 2020-12-08 04:06

I get this error if I click a button that starts the backgroundworker twice.

This BackgroundWorker is currently busy and cannot run multiple tasks concurrent         


        
4条回答
  •  无人及你
    2020-12-08 04:20

    Although not the case originally asked by the OP, this can also happen due to a race condition (happened to me now, and looked for an answer) if you're using a Background worker in some sort of a producer-consumer pattern.

    Example:

    if (BckgrndWrkr == null)
    {
        BckgrndWrkr = new BackgroundWorker(); 
        BckgrndWrkr.DoWork += DoWorkMethod;
        BckgrndWrkr.RunWorkerAsync();     
    }
    else if (!BckgrndWrkr.IsBusy)
    {
        BckgrndWrkr.RunWorkerAsync();
    }
    

    In this case there's a race condition: first instance instantiates a new background worker, 2nd instance reaches the else if and starts the background worker, before 1st instance reaches the RunWorkerAsync of the if block, and when it does it throws the error.

    This can be avoided by adding a lock to the entire if + if else section.

提交回复
热议问题