I have a WPF project, I need to send my heavy process to another thread and then get the result and send it to main thread. The expensive operation is to retrieve data from the database and populate a datagrid with data and then send it to main thread to be added to a grid. I created a thread, instantiate and run it:
Thread thread = new Thread(new ThreadStart(myHeavyProcess));
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
Here is my method:
private void myHeavyProcess()
{
DataGrid datagrd = new DataGrid();
//....
//populate the datagrid with data
//...
grdCharts.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)(() => grdCharts.Children.Add(datagrd )));
}
grdCharts is created in main thread and datagrd is created in the new thread, int the last line I tried to add the datagrd to grdcharts using Dispatcher as it is from a different thread.
The question is that since grdCharts is in the main thread and datagrd in the new thread how can I add datagrd to grdCharts ? or in general how can we copy one UIElement from a thread to another?
Note: I need to populate datagrid in another thread since it is the expensive process I was talking about.