使用BackgroundWorker调用WPF-GUI-Changes时出现异常

时间:2012-04-19 07:36:44

标签: c# wpf exception backgroundworker

我想通过操纵不透明度值来设置GUI上的Control透明。 因此,我在WPF-Form的构造函数上初始化BackgroundWorker,如:

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

之后,我的GUI等待一个由另一个类

触发的事件
soundController = new SoundController();
soundController.VolumeChanged +=new SoundController.VolumeChangedEventHandler(VolumeChanged);

在事件处理程序上,我最终将启动volumeWorker(BGW)来操作GUI:

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

但是在BackgroundWorkers ChangeEvent上,每次都有一个InvalidOperationException。有人知道吗?

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;
}

1 个答案:

答案 0 :(得分:1)

您无法直接在UI线程之外更改UI,因为UI控件是在UI线程上创建的。请改用Dispatcher.InvokeBeginInvoke方法。