Windows Phone: how to tell when Deployment.Current.Dispatcher.BeginInvoke has completed?

こ雲淡風輕ζ 提交于 2019-12-19 03:59:36

问题


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

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

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.

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.

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

Thanks.

Philip


回答1:


It's very easy ;)

// 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

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



来源:https://stackoverflow.com/questions/9453553/windows-phone-how-to-tell-when-deployment-current-dispatcher-begininvoke-has-co

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!