WinRT - 在保持UI响应的同时加载数据

Pau*_*els 6 .net c# microsoft-metro windows-8 windows-runtime

我正在开发一个Windows Metro应用程序,并且我遇到了一个UI无法响应的问题.据我所知,原因如下:

    <ListView
...
        SelectionChanged="ItemListView_SelectionChanged"            
...
Run Code Online (Sandbox Code Playgroud)

此事件在此处理:

    async void ItemListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (this.UsingLogicalPageNavigation()) this.InvalidateVisualState();

        MyDataItem dataItem = e.AddedItems[0] as MyDataItem;
        await LoadMyPage(dataItem);
    }

    private async Task LoadMyPage(MyDataItem dataItem)
    {            
        SyndicationClient client = new SyndicationClient();
        SyndicationFeed feed = await client.RetrieveFeedAsync(new Uri(FEED_URI));                    

        string html = ConvertRSSToHtml(feed)
        myWebView.NavigateToString(html, true);            
    }
Run Code Online (Sandbox Code Playgroud)

LoadMyPage需要一段时间才能完成,因为它从Web服务获取数据并将其加载到屏幕上.然而,看起来UI正在等待它:我的猜测是,直到上述事件完成.

所以我的问题是:我能做些什么呢?有没有更好的事件我可以挂钩,还是有其他方法来处理这个?我考虑过开始一个后台任务,但这对我来说似乎有些过分.

编辑:

只是为了澄清这个问题的规模,我说的是最多3到4秒没有反应.这绝不是一项长期工作.

编辑:

我已经尝试了下面的一些建议,但是,该SelectionChanged函数的整个调用堆栈正在使用async/await.我已经跟踪了这句话:

myFeed = await client.RetrieveFeedAsync(uri);
Run Code Online (Sandbox Code Playgroud)

在完成之前似乎没有继续处理.

编辑:

我意识到这将转变为战争与和平,但下面是使用空白的地铁应用程序和按钮复制问题:

XAML:

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
    <StackPanel>
        <Button Click="Button_Click_1" Width="200" Height="200">test</Button>
        <TextBlock x:Name="test"/>
    </StackPanel>
</Grid>
Run Code Online (Sandbox Code Playgroud)

代码背后:

    private async void Button_Click_1(object sender, RoutedEventArgs e)
    {
        SyndicationFeed feed = null;

        SyndicationClient client = new SyndicationClient();
        Uri feedUri = new Uri(myUri);

        try
        {
            feed = await client.RetrieveFeedAsync(feedUri);

            foreach (var item in feed.Items)
            {       
                test.Text += item.Summary.Text + Environment.NewLine;                    
            }
        }
        catch
        {
            test.Text += "Connection failed\n";
        }
    }
Run Code Online (Sandbox Code Playgroud)

Jef*_*and 5

试一试......

SyndicationFeed feed = null;

SyndicationClient client = new SyndicationClient();

var feedUri = new Uri(myUri);

try {
    var task = client.RetrieveFeedAsync(feedUri).AsTask();

    task.ContinueWith((x) => {
        var result = x.Result;

        Parallel.ForEach(result.Items, item => {
            Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
            () =>
            {
                test.Text += item.Title.Text;
            });
       });     
   });
}
catch (Exception ex) { }
Run Code Online (Sandbox Code Playgroud)

我在我的机器上尝试使用Grid应用程序模板向应用程序添加按钮.我可以来回滚动项目网格,同时更新页面标题没有问题.虽然我没有很多项目,但它的速度非常快,所以很难100%肯定.