0

I am getting an exception and I cannot see why I am getting this. I want to update a DataGrid with data from SQL.

The problem seems to be connected to my ObservableCollection..

Here is the code:

private void Refresh()
{
    new Thread(() =>
    {
        List<DatabaseEntry> entries = GetBrokenJobs();
        Dispatcher.CurrentDispatcher.Invoke(() =>
        {
           UpdateUi(entries);
        });
    }).Start();
}

private void UpdateUi(List<DatabaseEntry> entries)
{
    Jobs.Clear();//<== !!! Exception origin !!!
    foreach (var jobName in entries.SelectMany(x => x.JobBezeichnung as string).ToList())
    {
       Jobs.Add(jobName.ToString());
    }
}

The Exception is saying I cannot modify the "SourceCollection" when I am not on Dispatcher-Thread...

But I am Invoking the calling method on the Dispatcher ?!

What am I missing here ? Where is the fault ?

5
  • 1
    You can only update the observablecollection from the UI-dispatcher. You start a new thread use the dispatcher of the thread. that is not equal to the dispatcher of the ui
    – Jehof
    Mar 14, 2016 at 12:57
  • So when initializing my Viewodel can I add a static Dispatcher of the UI-Thread and then take that one ?
    – Felix D.
    Mar 14, 2016 at 12:57
  • 1
    @Jehof you were right ^^ I solved it. I took the original Dispatcher of the UI-Thread
    – Felix D.
    Mar 14, 2016 at 13:01
  • That said, you don't need a Thread at all. All your thread does is invokes the method in UI thread. You can just do it without the thread. Mar 14, 2016 at 13:05
  • @SriramSakthivel I want to do the SELECT in background cause it takes some time ... and freezes the UI... The actual UI-Update needs to be on the dispatcher ..
    – Felix D.
    Mar 14, 2016 at 13:06

2 Answers 2

1

You can run on UI thread like this

 Application.Current.Dispatcher.Invoke(() =>
 {
    UpdateUi(entries);
 });
1
  • oh nice :D seems to be a better solution than mine ^^
    – Felix D.
    Mar 14, 2016 at 13:07
0

I fixed it by creating a static variable in my ViewModel:

public static Dispatcher UI_Dispatcher { get; set; }

then in my ViewModel:

public MainViewModel(Main window)
{
    UI_Dispatcher = Dispatcher.CurrentDispatcher; //Since we are on the UI-Thread when passing this piece of code this is the right Dispatcher
}

Later I just Invoked on the UI_Dispatcher.Invoke().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.