Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

c# - 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)

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...