I know that this subject has already been treated several times but the codes presented are for the most part very complicated and do not correspond or little to mine. So my problem is that when executing my code I get the error message of the title
I have a datagrid in my main thread that I want to modify in the secondary thread:
private void BtnThread_Click(object sender, RoutedEventArgs e)
{
thread = new Thread(new ThreadStart(ThreadLoop));
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
public void ThreadLoop()
{
DateTime? dtdebTemp = new DateTime();
DateTime? dtfinTemp = new DateTime();
DataGrid dg = new DataGrid();
DataGridTextColumn col = new DataGridTextColumn();
col.Header = "test";
Application.Current.Dispatcher.Invoke(new Action(() =>
{
dtdebTemp = dtDeb.Value;
dtfinTemp = dtFin.Value;
dg = MyDataGridOfMainThread;
}));
dg.Columns.Add(col);
}
I'm trying for the moment just to add a test column but it's impossible. Thank you for your future answer.
Edit :
I found the answer it was enough to make the modification of the datagrid inside a Dispatcher like this :
public async void ThreadLoop()
{
DateTime? dtdebTemp = new DateTime();
DateTime? dtfinTemp = new DateTime();
DataGrid dg = new DataGrid();
DataGridTextColumn col = new DataGridTextColumn();
col.Header = "test";
Application.Current.Dispatcher.Invoke(new Action(() =>
{
dtdebTemp = dtDeb.Value;
dtfinTemp = dtFin.Value;
dg = MyDataGridOfMainThread;
}));
await this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (SendOrPostCallback)delegate
{
dg.Columns.Add(col);
}, null);
}