views:

258

answers:

2

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?

+3  A: 

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

C. Ross
+7  A: 

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.

itowlson
Good call. I agree this is a better answer, for the limited case specified.
C. Ross