简体   繁体   中英

Changing the property of a control from a 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);
    }
}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM