wpf后台线程更新UI控件

时间:2014-03-24 20:44:47

标签: c# .net multithreading

我有一个工作的应用程序,它将新的RibbonTab和一个新的子控件添加到网格中。

我想将此操作放到后台线程上,因为子控件可能需要一段时间才能从数据库中收集数据等。

到目前为止,我有以下代码:

Ribbon Ribbon_Main = new Ribbon();
Grid Grid_Main = new Grid();

Thread newthread2 = new Thread(new ThreadStart(delegate { Graphing_Template.add_report(); }));
newthread2.SetApartmentState(ApartmentState.STA);  //Is this required?
newthread2.Start();


Class Graphing_Template()
{
  static void add_report()
   {
     RibbonTab rt1 = new RibbonTab();
     MainWindow.Ribbon_Main.Items.Add(rt1);
     // Create control with information from Database, etc.
     // add control to MainWindow.Grid_Main
   }
}

我希望在后台创建新的报表控件,然后在准备就绪时将其添加到主UI中。

我选择的解决方案是:

     BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += delegate(object s, DoWorkEventArgs args)
            {
                DataTable dt1 = new DataTable();
               ---- Fill DataTable with
                args.Result = datagrid_adventureworks_DT();
            };

 worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args)
            {
                DataTable dt1 = (DataTable)args.Result;
                Datagrid_Main.ItemsSource = dt1.AsDataView();
            };

1 个答案:

答案 0 :(得分:1)

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        Test4();

    }
    private void Test1()
    {
        while (true)
        {
            this.Title = DateTime.Now.ToString();
            System.Threading.Thread.Sleep(5000); //locks up app
        }
    }
    private void Test2()
    {
        var thd = new System.Threading.Thread(() => {
            while (true)
            {
                this.Title = DateTime.Now.ToString(); //exception
                System.Threading.Thread.Sleep(5000);
            }            
        });
        thd.Start();
    }

    private void Test3()
    {   //do the work on the background thread
        var thd = new System.Threading.Thread(() =>
        {
            while (true)
            {   //use dispatcher to manipulate the UI
                this.Dispatcher.BeginInvoke((Action)(() 
                    => { this.Title = DateTime.Now.ToString(); 
                }));

                System.Threading.Thread.Sleep(5000);

                //there's nothing to ever stop this thread!
            }
        });
        thd.Start();
    }

    private async void Test4()
    {   //if you are using .Net 4.5 you can use the Async keyword
        //I _think_ any computation in your async method runs on the UI thread, 
        //so don't use this for ray tracing, 
        //but for DB or network access your workstation can get on with 
        //other (UI) work whilst it's waiting
        while (true)
        {
            await Task.Run(() => { System.Threading.Thread.Sleep(5000); });
            this.Title = DateTime.Now.ToString();
        }
    }