Search code examples
c#wpfmultithreadingbackgroundworker

WPF/C# Cancelling BackgroundWorker call outside DoWork


I have a BackgroundWorker DoWork function as follows

    private void WorkerGetFeedData(object sender, DoWorkEventArgs args)
    {
            _feed.FetchUserData(_userNameCollection);
    }

The FetchUserData is a function in another class(whose object is _feed) in another project in the same solution. The data fetch process takes considerable time and I'd like for the user to be able to cancel the process if necessary. How do I convey a cancel operation from the user to a function call elsewhere and just stop it?


Solution

  • You can use BackgroundWorker.CancelAsync method. Here's more info with example: MSDN

    To be more exact to your problem, pass the worker to FetchUserData. It is the sender parameter. Then in the FetchUserData function you can check if the flag BackgroundWorker.CancellationPending is set and finish your method.

    void FetchUserData(IEnumerable<Users> userNameCollection, BackgroundWorker worker)
    {
        // ...
    
        if(worker.CancellationPending)
        {
            // Finish method..
        }
    }
    

    And the WorkerGetFeedData method:

    private void WorkerGetFeedData(object sender, DoWorkEventArgs args)
    {
            var worker = sender as BackgroundWorker;
            if(worker != null)
                _feed.FetchUserData(_userNameCollection, worker);
    }