0

On a button press I call a background worker to change the colour of some text, and in the DoWork method it creates a new object and executes one of its methods. Here is the code:

    private void StartProcessButton_Click(object sender, EventArgs e)
    {
        FirstTimeBackgroundWorker.RunWorkerAsync(GenKeyLabel.ForeColor = Color.DodgerBlue);

    }

And the DoWork method...

    private void FirstTimeBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
    {  
        KeyFile k = new KeyFile();
        k.CreateDummyFile(DLetter);

    }

[The CreateDummyFile effectively does a bunch of file processing, such as copying,deleting and creating files (up to 4.0MB). Throughout I call the ReportProgress method and change some GUI elements on the form, however as it does it in one chunk I cant see the constant progress or the GUI elements change]

Now it does what its supposed to inside the CreateDummyFile method, however it executes it as if it wasn't in another thread (like when you press a button to do something and the form would freeze, and then just show the final result). Any ideas why this is? What I am doing wrong?

There is a lot of code in that class that gets executed so I can't just place it inside the DoWork method.

EDIT: Removed all of the ReportProgress's and it still only changes one of my GUI elements. (All I do is change the font.forecolour. Apart from this I am changing the text on a status strip...

4

1 に答える 1

1

BackgroundWorkerFirstTimeBackgroundWorker_DoWorkのイベントのハンドラーとしてを追加する必要があります。DoWork

FirstTimeBackgroundWorker.DoWork += FirstTimeBackgroundWorker_DoWork;

また、UIをコールバックして更新する場合は、バックグラウンドスレッドからではなく、UIスレッドで更新するようにしてください。

于 2013-01-11T19:39:20.283 に答える