I have a working app that adds new a new RibbonTab and a new child control to the Grid.
I would like to put this action onto a background thread as the child control can take a while to gather data from a database, etc.
I have the following code so far:
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
}
}
I would like the new report control to be created in the background and then added to the Main UI when it is ready.
The solution I went with is:
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();
};
Ribbonand aGridobject on the caller thread.BackgroundWorkerclass. It fires off a thread with an in-built mechanism to communicate with the original thread. If you're doing anything more complex, though,Taskis going to be a better choice.