【发布时间】:2012-02-17 01:27:36
【问题描述】:
我继承了一些通过 WCF 服务查询数据库的代码,然后在完成后使用回调。我正在尝试向该回调添加一些代码,以在处理数据时更新 UI。我发现在回调期间我无法更新 UI:
client.GetDataAsync();
client.GetDataCompleted += new EventHandler<GetDataCompletedEventArgs>(GetDataCompleted);
void GetDataCompleted(object sender, GetDataCompletedEventArgs e)
{
// Loop through the data
// ...
textBlock1.Text= "test1";
Dispatcher.BeginInvoke(() => textBlock1.Text= "test2" );
var thread = new Thread(() =>
{
// textBlock1.Text= "test3"; (this throws a cross-thread access exception)
Dispatcher.BeginInvoke(() =>
{
textBlock1.Text= "test4";
});
}
thread.Start();
// ...
Debug.WriteLine("done");
}
在(显然)整个回调完成之前,这些东西都不会更新 UI。这篇文章:
What thread calls the completed event handler on silverlight WCF calls?
建议回调在主 UI 线程上运行,因此 BeginInvoke 调用应该是不必要的。即使我在上面的代码中添加了各种延迟,它仍然不起作用。这可能吗?有没有更好的方法来做到这一点?
(这是对此的后续问题:Multiple asynchronous UI updates in Silverlight)
【问题讨论】:
-
(有更好的方法吗?)您使用的是什么版本的 Silverlight?新的 Task.Factory.FromAsync 是一种享受。您摆脱了事件处理程序,代码变得更具可读性,并且您可以更好地控制执行的位置/时间。
标签: c# wcf silverlight asynchronous callback