Search code examples
c#backgroundworker

How to report progress from within a class to a BackgroundWorker?


My WinForm calls a class which performs some copying actions. I'd like to show the progress of this on a form.

I'd like to use the Backgroundworker, but I don't know how to report progress from the class to the form (/backgroundworker)


Solution

  • use the OnProgressChanged() method of the BackgroundWorker to report progress and subscribe to the ProgessChangedEvent of the BackgroundWorker to update the progress in your GUI.

    Your copy class knows the BackgroundWorker and subscribes to ProgressChanged. It also exposes an own ProgressChanged event that's raised by the event handler for the background worker's ProgressChanged event. Finally your Form subscribes to the ProgressChanged event of the copy class and displays the progress.

    Code:

    public class CopySomethingAsync
    {
        private BackgroundWorker _BackgroundWorker;
        public event ProgressChangedEventHandler ProgressChanged;
    
        public CopySomethingAsync()
        {
            // [...] create background worker, subscribe DoWork and RunWorkerCompleted
            _BackgroundWorker.ProgressChanged += HandleProgressChanged;
        }
    
        private void HandleProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (ProgressChanged != null)
                ProgressChanged.Invoke(this, e);
        }
    }
    

    In your form just subscribe to the ProgressChanged event of CopySomethingAsync and display the progress.