2012-05-24 90 views
0

我有包含QueryData方法的视图模型:Dispatch.BeginInvoke我究竟做错了什么?

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

调用此方法从timer_Tick事件处理程序的每个10秒。然后数据被异步查询,然后执行回调。那里查询的数据,应该插入Observable集合(不是STA线程 - >开始Invoke)。它正确地进入回调,但不执行内部Dispatcher.CurrentDispatcher.BeginInvoke的代码。

我在做什么错了?

+0

事我会先检查:是'错误== null'? '.Pieces生产的'有物品吗?添加一些日志记录将有助于诊断正在发生的事情。 –

+0

错误不为空。开始调用行被执行。 PiecesProduced包含项目。 – TheJoeIaut

+0

还有什么是你调用堆栈在这一点上发生了什么?您的代码不会被执行,直到调度完成其目前的工作 - 而在这之前,分派需要给予机会执行。是否还有其他事情阻止了Dispatcher?是您'timer'实际上是一个'DispatcherTimer',还是有别的东西在那个点上的UI长时间运行? –

回答

1

这不起作用,因为您呼叫Dispatcher.CurrentDispatcher是在不同的线程运行的方法中。这不是您要找的Dispatcher

相反,你应该设置一个局部变量的当前Dispatcher调用你的方法之前,然后它会被提升到您的拉姆达为您提供:

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