C#,使用来自其他类的后台工作程序更新进度条 [英] C#, Updating a Progress Bar Using Background Worker From a Different Class

查看:113
本文介绍了C#,使用来自其他类的后台工作程序更新进度条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更新主窗体上的进度条,并在不同的班级完成工作.例如:

I am attempting to update the progress bar on a main form with the work being done in a different class. For example:

private void transfer_Click(object sender, EventArgs e)
{
    Guid aspnetUserId = Guid.Parse(System.Configuration.ConfigurationSettings.AppSettings["ASPNetUserID"]);
    WC1toWC2Transfer transfer = new WC1toWC2Transfer(aspnetUserId);

    backgroundWorker1.RunWorkerAsync(transfer);  
}

然后在后台方法中实际调用该方法:

And then in the background method actually call the method:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    WC1toWC2Transfer transfer = e.Argument as WC1toWC2Transfer;
    transfer.WC1ToWC2EmployerTransfer(log, wc1ConnStr, wc2ConnStr, progressBar1);
}

在WC1ToWC2EmployerTransfer方法中,我设置进度条最大值,并在每次将任何内容传输到此方法时更新值,但是当我这样做时,什么也没有发生.该方法内部有代码可以在数据库中运行存储过程,但是一旦它到达了代码的那一部分,它就会停止调试,而我必须再次运行该过程.

In the WC1ToWC2EmployerTransfer method, I'm setting the progress bar maximum and updating the value everytime something is transferred to the database in this method, but when I do this nothing happens. There's code inside the method that runs a stored procedure in a database, but as soon as it hits that portion of the code, it stops debugging and I have to run the process again.

我在这里做错什么了吗?我是否需要重写已有的内容,以便实际的方法以主要形式而不是在不同的类中?我是一名初级开发人员(几个月前才开始),所以请原谅我做错了什么事情,或者我做得不够充分.

Am I doing something wrong here? Do I need to rewrite what I have so the actual methods are in the main form and not in a different class? I'm a junior developer (just started a few months ago) so forgive me if I'm doing something blatantly wrong or if I didn't explain this well enough.

任何帮助将不胜感激.

推荐答案

除非您位于主线程上,否则您将无法更改UI.

You cant alter the UI unless you are on the main thread, which you BackgroundWorker will not be.

您需要做的是在主窗体中创建一个事件处理程序,以处理背景工作人员的ProgressChanged事件.

What you need to do is create an event handler in the main form to handle the backgroundworker's ProgressChanged event.

例如

// this method should be in your main form.
private void backgroundworker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    // update your progress bar here.
}

在后台工作人员中,您呼叫 ReportProgress 方法,该方法将触发ProgressChanged事件.

In your background worker, you call the ReportProgress method which will fire the ProgressChanged event.

此处.

这篇关于C#,使用来自其他类的后台工作程序更新进度条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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