将数据加载到WPF中的数据网格时,如何使用线程显示进度条? [英] How to display the Progress Bar using thread when load data to data grid in WPF?

查看:128
本文介绍了将数据加载到WPF中的数据网格时,如何使用线程显示进度条?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用于在WPF中将数据加载到数据网格时使用线程概念显示进度条.使用以下代码.

Have used to display the progress Bar using thread concept when load data to data grid in WPF. the following codes are used.

public partial class MainWindow : Window
    {
        private  bool firstLoad = true;      
        private delegate void SimpleDelegate();
        DataSet ds = new DataSet();
        CollectionView view;
        public MainWindow()
        {
           InitializeComponent();
            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += new DoWorkEventHandler(RunOnBGThread);
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BGThreadWorkDone);
            worker.RunWorkerAsync();
            BackgroundWorker worker1 = new BackgroundWorker();
            worker1.DoWork += new DoWorkEventHandler(RunOnBGThreadProgressBas);
            worker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BGThreadWorkDone);
            worker1.RunWorkerAsync();		
        }
        private void RunOnBGThread(object sender, DoWorkEventArgs e)
        {
            LoadProcess();
        }       
        private void LoadProcess()
        {
            try
            {
                SimpleDelegate del1 = delegate()
                {                                        
                    if (firstLoad)
                    {
                         
                        firstLoad = false;                       
                        SqlHelper.FillDataset(Application.Current.Properties["constr"].ToString(), CommandType.Text, "select * from account a left join transscheme ts on ts.schemecode = a.scheme where dist_code=''c'' order by acct_code", ds, new String[] { "tab_grdbindload" });
                         this.DataContext = ds.Tables["tab_grdbindload"];
                         view = (CollectionView)(CollectionViewSource.GetDefaultView(ds.Tables["tab_grdbindload"]));
                         grd_boview.ItemsSource = view;    
                     
                    }                    
                };
                this.Dispatcher.BeginInvoke(DispatcherPriority.Send, del1);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }		
        }
        private void BGThreadWorkDone(object sender, RunWorkerCompletedEventArgs e)
        {
            prgbar.Visibility = Visibility.Collapsed;  
        }
        private void RunOnBGThreadProgressBas(object sender, DoWorkEventArgs e)
        {
            Duration dd = new Duration(new TimeSpan(10));  //creating an object of the duration class.
            DoubleAnimation da = new DoubleAnimation(30.0, dd); 
           prgbar.BeginAnimation(ProgressBar.ValueProperty, da);
        }
    }
}


在上面的代码中,引发了以下错误调用线程无法访问该对象,因为其他线程拥有它".代码行"prgbar.BeginAnimation(ProgressBar.ValueProperty,da);".
请向我建议如何在加载进度条时使用线程.


In this above code the following error was thrown "The calling thread cannot access this object because a different thread owns it." the line of code "prgbar.BeginAnimation(ProgressBar.ValueProperty, da);".
Please advice me how to use the thread while load the progress bar.

推荐答案

该方法也不应在非UI线程上调用,而应在UI线程上调用使用Dispatcher.InvokeDispatcher.BeginInvoke.您无法从非UI线程在UI上调用任何内容.

在我过去的答案中,您将找到有关其工作原理的详细说明和代码示例:
Control.Invoke()与Control.BeginInvoke() [ ^ ],
Treeview Scanner和MD5的问题 [如何获取keydown事件在vb.net中的不同线程上操作 [启用禁用+多线程后控件事件不会触发 [ ^ ].


这是与正确调用所需的委托一起使用的方法:

This method also should not be called on you non-UI thread but invoked on the UI thread using Dispatcher.Invoke or Dispatcher.BeginInvoke. You cannot call anything on UI from non UI thread.

You will find detailed explanation of how it works and code samples in my past answers:
Control.Invoke() vs. Control.BeginInvoke()[^],
Problem with Treeview Scanner And MD5[^].

See also more references on threading:
How to get a keydown event to operate on a different thread in vb.net[^],
Control events not firing after enable disable + multithreading[^].


This is how to work with delegate needed for invocation properly:

void UpdateProgressBar(Dispatcher dispatcher, ProgressBar progressBar, double value) {
dispatcher.BeginInvoke(
    new Action<ProgressBar, double>(
        (progressBarInstance, newValue) => {
            progressBarInstance.Value = newValue;
        }), progressBar, value);
} //UpdateProgressBar



匿名委托实例的主体位于上面的"{}"之间.

—SA



The body of the anonymous delegate instance comes between "{}" above.

—SA


这篇关于将数据加载到WPF中的数据网格时,如何使用线程显示进度条?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆