Search code examples
c#winformsmultithreadingbackgroundworker

Using BackgroundWorker to retrieve details of last selected item from a list


In my application I have a DataGrid that is populated from a database. When I click one of the items, its details are retrieved and passed to UI. Getting item details is a coslty operation so I use a BackgroundWorker to handle it. When I select another item during the retrieval, I would like to abort current operation and start another one using new item id. What;s the best way to do it? I tried to put this in DataGrid CellContentClick hanlder:

if(worker.IsBusy)
{
    worker.CancelAsync();
}

but I always get details of first selected item.


Solution

  • Ok, I figured it out myself. Firstly i scattered following blocks all over worker_DoWork handler:

    if(worker.CancellationPending)
    {
        e.Cancel = true;
        return;
    }
    

    I also prevented execution of worker.RunWorkerAsync(), when worker.CancellationPending is true. To achieve my goal I added the following code to my RunWorkerCompleted handler:

    if(!e.Cancelled)
    {
        //update UI
    }
    else
    {
        //retrieve details of new item
    }