Changing the property of a control from a BackgroundWorker C#

泪湿孤枕 提交于 2019-12-05 02:36:48

问题


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?


回答1:


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.




回答2:


You need to use InvokeRequired and BeginInvoke.
This page tells you about how to do it. Here's the MSDN page.



来源:https://stackoverflow.com/questions/1697784/changing-the-property-of-a-control-from-a-backgroundworker-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!