Search code examples
c#wpfexceptionbackgroundworker

Exception while calling WPF-GUI-Changes with BackgroundWorker


I want to set a Control on my GUI transparent through manipulating opacity value. Therefore, I initialize a BackgroundWorker on the constructor of my WPF-Form like :

volumeWorker = new BackgroundWorker();
volumeWorker.DoWork += new DoWorkEventHandler(VolumeBarDoWork);
volumeWorker.ProgressChanged += new ProgressChangedEventHandler(VolumeBarChanged);
volumeWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(VolumeBarCompleted);
volumeWorker.WorkerReportsProgress = true;

After that, my GUI waits for an event, which is triggered by another class

soundController = new SoundController();
soundController.VolumeChanged +=new SoundController.VolumeChangedEventHandler(VolumeChanged);

On the event handler i finally will start the volumeWorker (BGW) to manipulate the GUI:

private void VolumeChanged(float pVolume)
{
    Logger.InfoWrite("Event raised ## New volume : {0}", pVolume);
    volumeWorker.RunWorkerAsync();
}

But on BackgroundWorkers ChangeEvent, i got a InvalidOperationException every time.Did anyone got a idea?

private void VolumeBarDoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker worker = sender as BackgroundWorker;
    Logger.InfoWrite("Worker");
    for(int _opacity = 99 ; _opacity >= 0 ; _opacity--)
    {
        Logger.InfoWrite("Start on {0}", _opacity);
        worker.ReportProgress(_opacity);
        System.Threading.Thread.Sleep(20)
    }
    e.Result = e.Argument;
}

private void VolumeBarChanged(object sender, ProgressChangedEventArgs e)
{
    this.volumeBar.Opacity -= 0.01f;
    Logger.InfoWrite("Changed opacity to : {0} on {1}", this.volumeBar.Opacity, e.ProgressPercentage);
}

private void VolumeBarCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    Logger.InfoWrite("Completed");
    this.volumeBar.Opacity = 0.0f;
}

Solution

  • You cannot change UI directly outside the UI thread, since the UI controls are created on the UI thread. Use the Dispatcher.Invoke or BeginInvoke method instead.