从一个BackgroundWorker C#更改控件的属性 [英] Changing the property of a control from a BackgroundWorker C#

查看:623
本文介绍了从一个BackgroundWorker C#更改控件的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从目录加载一堆文件,虽然它的加载,显示进度条的状态,以及显示其正在处理的文件的标签。

I'm trying to load a bunch of files from a directory, and while it's loading, display a progress bar status, as well as a label that displays which file is being processed.

private void FileWorker_DoWork(object sender, DoWorkEventArgs e)
{
    for (int i = 0; i < Files.Length; i++)
    {
        Library.AddSong(Files[i]);
        FileWorker.ReportProgress(i);
    }
}



目前,它正确地处理一切,与进步栏显示状态正常,但是当我试图改变标签的文本(lblfile.text)它说,它不能改变在不同的线程控制。 ?有没有办法来改变从Fileworker lblfile.text文

At the moment it processes everything properly, and the progress bar displays status properly, but when i try to change the label's text (lblfile.text) it says it cannot change a control on a different thread. Is there a way to change the text of lblfile.text from the Fileworker?

推荐答案

作为的C。罗斯说,你可以做到这一点直接使用Control.Invoke家族的方法,但它可能会更容易 - 也许更地道 - 通过处理BackgroundWorker.ProgressChanged事件做间接的影响。虽然DoWork的是在后台线程上提出,ProgressChanged引发的UI线程。因此,在更新你的ProgressChanged文字不需要调用。

As C. Ross says, you can do this directly using the Control.Invoke family of methods, but it may be easier -- and is probably more idiomatic -- to do it indirectly by handling the BackgroundWorker.ProgressChanged event. While DoWork is raised on the background thread, ProgressChanged is raised on the UI thread. So updating your text in ProgressChanged doesn't require Invoke.

此外,这使你的工人功能免费UI的依赖,这将使它更容易进行测试。

In addition, this keeps your worker function free of UI dependencies which will make it easier to test.

这篇关于从一个BackgroundWorker C#更改控件的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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