开发者

Changing the property of a control from a BackgroundWorker C#

开发者 https://www.devze.com 2022-12-10 09:09 出处:网络
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.

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.

pri开发者_如何学Pythonvate 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?


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号