-1

I can't explain this with my own words, so here's the situation:

myBindingSource.Add(new myElement());
SetDataSource(myBindingSource);
myBindingSource.Add(new myElement());

I always catch an exception (a cross-thread exception) on the second call of Add. Here's the SetDataSource void:

delegate void SetDataSourceCallback(BindingSource db);
private void SetDataSource(BindingSource db)
{
        if (myDataGridView.InvokeRequired)
        {
            SetDataSourceCallback d = new SetDataSourceCallback(SetDataSource);
            myDataGridView.Invoke(d, new object[] { db });
        }
        else
        {
            myDataGridView.DataSource = db;
        }
}

I can't understand why this keep happening!

devgianlu
  • 1,547
  • 13
  • 25
  • It is not legal to update a data source from a worker thread. You need a ClearDataSource() method as well so you can reset the myDataGridView.DataSource property back to null. – Hans Passant Mar 28 '16 at 17:16
  • Use this answer: call using the WPF/UI main thread's dispatcher: http://stackoverflow.com/questions/11625208/accessing-ui-main-thread-safely-in-wpf – Ciprian Khlud Mar 28 '16 at 17:16

1 Answers1

1

Use the main UI thread's dispatcher to call safely any UI code from any other thread.

WPF cannot let you change any UI state from other thread than the "main" UI thread. So in general, if you have any state which changes UI, you should wrap it with the Dispatcher.Invoke code.

Application.Current.Dispatcher.Invoke(new Action(() => {
   myBindingSource.Add(new myElement());
   SetDataSource(myBindingSource);
   myBindingSource.Add(new myElement());
 }));
Ciprian Khlud
  • 434
  • 3
  • 6
  • 2
    While I like your answer, you could add a more detailed explanation as to why this is necessary. I think it would more adequately answer the question and make your answer stand out. – Michael J. Gray Mar 28 '16 at 17:30