从外部方法更新UI进度条

时间:2013-10-17 03:05:01

标签: c# wpf

所以这是我第一次尝试使用委托,事件,背景工作者,WPF ......几乎所有东西都是新的。我有一个外部类,它运行一个长期运行的方法,我想报告进度:

public class ShortFileCreator
{
    public void CreateShortUrlFile(string outputfilepath)
    {         
        foreach(string line in lines)
        {
                //work work work processing file
                if (ReportProgress != null)
                {
                //report progress that a file has been processed
                    ReportProgress(this, new ProgressArgs {TotalProcessed = numberofurlsprocessed
                                                         , TotalRecords = _bitlyFile.NumberOfRecords});
                }
        }
    }

    public delegate void ReportProgressEventHandler (object sender, ProgressArgs args);

    public event ReportProgressEventHandler ReportProgress;

    public class ProgressArgs : EventArgs
    {
        public int TotalProcessed { get; set; }
        public int TotalRecords { get; set; }
    }
}

在我的WPF表单中,我想启动CreateShortUrlFile方法并更新表单的进度条。

private void btnRun_Click(object sender, RoutedEventArgs e)
    {
       var shortFileCreator = new ShortFileCreator();           

        _worker = new BackgroundWorker
        {
            WorkerReportsProgress = true,
            WorkerSupportsCancellation = true
        };

        shortFileCreator.ReportProgress += ShortFileCreator_ReportProgress;

        _worker.DoWork += delegate(object s, DoWorkEventArgs args)
        {
            _bitlyFileWorker.CreateShortUrlFile(saveFileDialog.FileName);
        };

        _worker.RunWorkerAsync();
    }

    protected void ShortFileCreator_ReportProgress(object sender, ShortFileCreator.ProgressArgs e)
    {
        //update progress bar label
        txtProgress.Content = String.Format("{0} of {1} Records Processed", e.TotalProcessed, e.TotalRecords);
        //update progress bar value
        progress.Value = (double) e.TotalProcessed/e.TotalRecords;
    }

然而,当我运行它时,它处理一行然后我得到异常:调用线程无法访问此对象,因为另一个线程拥有它。其他什么线程拥有这个? ReportProgress事件不应该将ProgressArgs返回给任何订阅者吗?

1 个答案:

答案 0 :(得分:1)

这是因为其他线程无法触及ProgressBarTextBox之类的UI控件,在这种情况下,您尝试从BackgroundWorker线程更新它们。

解决这个问题的方法是Invoke回调到UI线程,你可以使用Dispatcher

来做到这一点
protected void ShortFileCreator_ReportProgress(object sender, ShortFileCreator.ProgressArgs e)
{
    Dispatcher.Invoke((Action)delegate
    {
       //update progress bar label
       txtProgress.Content = String.Format("{0} of {1} Records Processed", e.TotalProcessed, e.TotalRecords);
       //update progress bar value
       progress.Value = (double) e.TotalProcessed/e.TotalRecords;
    });
}
相关问题