I have a WPF Datagrid with the .ItemSource set to a Datatable. In a background thread, a new Datatable is generated, and needs to be added to the binded Datatable.
When i do CurrentTable.Merge(NewTable) from the UI thread, the whole UI freezes for a couple of seconds (since there are so many rows to be added).
When I do CurrentTable.Merge(NewTable) from the background thread, and immediately after that call Datagrid.Items.Refresh in the UI thread, the freeze disappears.
BUT: If the user happens to scroll the grid in the seconds between the .Merge started and the .Refresh finished, exceptions are generated by the Datagrid, and the app crashes.
So how can I safely merge the two, without freezes, and without crashes?
UPDATE:
I found part of the solution, by wrapping my Datatables in a Bindingsource, i can merge from the background thread without crashes:
BindingSource bs = new BindingSource();
DataTable dt = new DataTable();
bs.DataSource = dt;
bs.SuspendBinding();
bs.RaiseListChangedEvents = false;
dt.BeginLoadData();
//== Begin background thread
dt.EndLoadData();
bs.RaiseListChangedEvents = true;
bs.ResumeBinding();
bs.ResetBindings(true);
However, the last call (ResetBindings) has the same effect as setting a new .ItemSource: The user looses his current position in the grid. And this was just what I wanted to avoid, and the reason i choose for .Merge in the first place: to alter the existing table without having to set a new .ItemSource for the Datagrid.
So i'm a little bit closer, but still no cigar!