0

I have a ViewModel which contains a QueryData method:

void QueryData() {
    _dataService.GetData((item, error) =>
    {
        if(error != null)
            return;
        Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
        {
            foreach(TimeData d in ((LineDetailData)item).Piecesproduced) {
                Produced.Add(d);
            }
        }), DispatcherPriority.Send);
    });
}

This method gets called each 10 seconds from a timer_Tick Event Handler. Then the Data is queried async and then the callback is executed. There the queried Data, should be inserted in an Observable Collection(not STA Thread -> begin Invoke). It correctly enter the callback, but the code inside Dispatcher.CurrentDispatcher.BeginInvoke isn't executed.

What am i doing wrong?

DmitryG
  • 17,677
  • 1
  • 30
  • 53
TheJoeIaut
  • 1,522
  • 2
  • 26
  • 59
  • Things I would check first: is `error == null`? Are there items in `.Piecesproduced`? Adding some logging would help to diagnose what's going on. – Dan Puzey May 24 '12 at 08:46
  • error is not null. The Begin Invoke line is executed. PiecesProduced contains items. – TheJoeIaut May 24 '12 at 09:02
  • What else is happening in your callstack at that point? Your code won't be executed until the Dispatcher finishes its current job - and before that, the Dispatcher needs to be given chance to execute. Is there something else going on that's blocking the Dispatcher? Is your `timer` actually a `DispatcherTimer`, or is there something else long-running on the UI at that point? – Dan Puzey May 24 '12 at 11:45
  • Step through in your debugger and watch the threads/call stack. See if an exception is killing the thread before it gets to it. Put a breakpoint on the loop and if it hits it, it is likely some invalid operation with the loop causing it to kill the thread. – erodewald May 24 '12 at 20:14

1 Answers1

1

This doesn't work because the you are calling Dispatcher.CurrentDispatcher inside a method that is running on a different thread. This isn't the Dispatcher you're looking for.

Instead, you should set a local variable to the current Dispatcher before calling your method, and then it will get lifted into your lambda for you:

void QueryData() 
{
    var dispatcher = Dispatcher.CurrentDispatcher;
    _dataService.GetData((item, error) =>
    {
        if(error != null)
            return;
        dispatcher.BeginInvoke(new Action(() =>
        {
            foreach(TimeData d in ((LineDetailData)item).Piecesproduced) {
                Produced.Add(d);
            }
        }), DispatcherPriority.Send);
    });
}
Abe Heidebrecht
  • 30,090
  • 7
  • 62
  • 66