从BackgroundWorker C# 更改控件的属性
我正在尝试从目录加载一堆文件,在加载时显示进度条状态以及显示正在处理哪个文件的标签。
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 的文本?
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);
}
}
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
作为 C. Ross 说,您可以使用 Control.Invoke 系列方法直接执行此操作,但通过处理 BackgroundWorker.ProgressChanged 事件间接执行此操作可能更容易,而且可能更惯用。 DoWork 在后台线程上引发,而 ProgressChanged 在 UI 线程上引发。因此,在 ProgressChanged 中更新文本不需要 Invoke。
此外,这可以让您的工作函数摆脱 UI 依赖,从而更容易测试。
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.
In addition, this keeps your worker function free of UI dependencies which will make it easier to test.
您需要使用 InvokeRequired 和BeginInvoke。
此页面告诉您如何执行此操作。
这是 MSDN 页面。
You need to use InvokeRequired and BeginInvoke.
This page tells you about how to do it.
Here's the MSDN page.