TheJoeIaut
TheJoeIaut

Reputation: 1532

Dispatch.BeginInvoke What am i doing wrong?

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?

Upvotes: 0

Views: 442

Answers (1)

Abe Heidebrecht
Abe Heidebrecht

Reputation: 30498

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);
    });
}

Upvotes: 1

Related Questions