Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
347 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...