重用BackgroundWorker,取消并等待它

Car*_*res 4 c# multithreading backgroundworker

假设您有一个搜索文本框,并且有一个搜索算法附加到TextChanged事件,该事件与BackgroundWorker一起运行.如果文本框中出现了新字符,我需要取消之前的搜索并再次运行.

我尝试在主线程和bgw之间使用事件,从前一个问题,但我仍然得到错误"当前很忙,不能同时运行多个任务"

    BackgroundWorker bgw_Search = new BackgroundWorker();
    bgw_Search.DoWork += new DoWorkEventHandler(bgw_Search_DoWork);

    private AutoResetEvent _resetEvent = new AutoResetEvent(false);

    private void txtSearch_TextChanged(object sender, EventArgs e)
    {
        SearchWithBgw();
    }

    private void SearchWithBgw()
    {
        // cancel previous search
        if (bgw_Search.IsBusy)
        {
            bgw_Search.CancelAsync();

            // wait for the bgw to finish, so it can be reused.
            _resetEvent.WaitOne(); // will block until _resetEvent.Set() call made
        }

        // start new search
        bgw_Search.RunWorkerAsync();   // error "cannot run multiple tasks concurrently"
    }

    void bgw_Search_DoWork(object sender, DoWorkEventArgs e)
    {
        Search(txtSearch.Text, e);
    }

    private void Search(string aQuery, DoWorkEventArgs e)
    {
        int i = 1;            
        while (i < 3)             // simulating search processing...
        {
            Thread.Sleep(1000);                           
            i++;

            if (bgw_Search.CancellationPending)
            {
                _resetEvent.Set(); // signal that worker is done
                e.Cancel = true;
                return;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

编辑以反映答案.不要重复使用BackgroundWorker,创建一个新的:

    private void SearchWithBgw()
    {   
        if (bgw_Search.IsBusy)
        {
            bgw_Search.CancelAsync();
            _resetEvent.WaitOne(); // will block until _resetEvent.Set() call made

            bgw_Search = new BackgroundWorker();
            bgw_Search.WorkerSupportsCancellation = true;
            bgw_Search.DoWork += new DoWorkEventHandler(bgw_Search_DoWork);
        }

        bgw_Search.RunWorkerAsync();        
    }
Run Code Online (Sandbox Code Playgroud)

Han*_*ant 8

当_resetEvent.WaitOne()调用完成时,工作线程实际上没有完成.它忙于从DoWork()返回并等待运行RunWorkerCompleted事件的机会(如果有的话).这需要时间.

没有可靠的方法来确保BGW以同步方式完成.阻止IsBusy或等待RunWorkerCompleted事件运行将导致死锁.如果你真的只想使用一个bgw,那么你必须排队请求.或者只是不要为小东西流汗并分配另一个bgw.它们的成本非常低.