如何将课程中的进度报告给BackgroundWorker? [英] How to report progress from within a class to a BackgroundWorker?

查看:45
本文介绍了如何将课程中的进度报告给BackgroundWorker?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的WinForm调用一个执行一些复制动作的类.我想在表单上显示进度.

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

我想使用Backgroundworker,但是我不知道如何报告从类到表单(/backgroundworker)的进度

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

推荐答案

使用 BackgroundWorker 的rel ="noreferrer"> OnProgressChanged()方法a>报告进度并订阅 ProgessChangedEvent BackgroundWorker中的>来更新GUI中的进度.

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.

您的复制类知道BackgroundWorker并订阅ProgressChanged.它还公开了自己的ProgressChanged事件,该事件由事件处理程序针对后台工作程序的ProgressChanged事件引发.最后,您的Form订阅副本类的ProgressChanged事件并显示进度.

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.

代码:

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);
    }
}

在表单中,只需订阅CopySomethingAsyncProgressChanged事件并显示进度即可.

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

这篇关于如何将课程中的进度报告给BackgroundWorker?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆