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

后端 未结 4 726
Happy的楠姐
Happy的楠姐 2020-12-09 11:31

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 k

4条回答
  •  心在旅途
    2020-12-09 12:17

    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.

提交回复
热议问题