Windows Phone:如何判断 Deployment.Current.Dispatcher.BeginInvoke 何时完成? [英] Windows Phone: how to tell when Deployment.Current.Dispatcher.BeginInvoke has completed?

查看:23
本文介绍了Windows Phone:如何判断 Deployment.Current.Dispatcher.BeginInvoke 何时完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过将数据加载部分放入后台线程而不是在页面加载时在前台运行来使 WP7 应用程序中的页面 UI 更具响应性.

I'm trying to make the UI of a page in a WP7 application more responsive by putting the data loading portion into a background thread rather than running in the foreground when the page loads.

线程代码本质上是处理一些数据并将项目添加到一个可观察的集合中;为了避免异常问题,我执行如下操作:

The thread code essentially works through some data and adds items to an observable collection; in order to avoid exception issues, I execute something like:

Deployment.Current.Dispatcher.BeginInvoke(() => { _events.Add(_newItem); });

以便将项目添加到集合中是在 UI 线程中完成的.

so that the addition of the item to the collection is done in the UI thread.

我现在遇到的问题是,代码的后续部分需要对集合执行 foreach 以找出在何处插入新项目,而不是仅仅添加它.不幸的是,我发现 UI 线程有时会在我处于 foreach 循环中时执行其 Add,从而立即破坏 foreach.

The problem I'm now hitting is that a subsequent part of the code needs to perform a foreach on the collection in order to figure out where to insert a new item rather than just add it. Unfortunately, what I'm finding is that the UI thread can sometimes perform its Add while I'm in the foreach loop, instantly breaking the foreach.

从我所做的阅读来看,一种方法是调用 EndInvoke() 以阻止后台线程,直到 UI 部分完成.不幸的是,看起来 Wp7/Silverlight 实现不支持 EndInvoke.

From the reading I've done, it looks like one approach would be to call EndInvoke() in order to block the background thread until the UI piece is done. Unfortunately, it looks like thw Wp7/Silverlight implementation doesn't support EndInvoke.

关于如何在开始 foreach 之前检查添加是否已完成的任何建议?

Any suggestions on how I can check that the Add has been completed before I start the foreach?

谢谢.

菲利普

推荐答案

很简单 ;)

// must be executed in background
foreach (Item item in Items)
{
    EventWaitHandle Wait = new AutoResetEvent(false);
    Deployment.Current.Dispatcher.BeginInvoke(() =>
    {
        _events.Add(_newItem);
        Wait.Set();
    });
    // wait while item is added on UI
    Wait.WaitOne();
}
// here all items are added

这种方法可以在需要同步后台和 UI 线程执行的任何地方使用

This approach you can use everywhere where you need synchronize background and UI thread execution

这篇关于Windows Phone:如何判断 Deployment.Current.Dispatcher.BeginInvoke 何时完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆