增量加载捕获并抛出异常Metro App

时间:2014-02-25 12:00:47

标签: c# windows-store-apps windows-8.1

目前我正在开发具有GridView的Metro应用程序,该应用程序填充滚动数据。为此,我必须实现ISupportIncrementalLoading接口。我这样做了,我的代码工作正常。但我想知道如果发生异常,如何从Exception函数抛出LoadMoreItemsAsync。以下是代码段。

public Windows.Foundation.IAsyncOperation<LoadMoreItemsResult> LoadMoreItemsAsync(uint count)
    {
        if (count > 50 || count <= 0)
        {
            // default load count to be set to 50
            count = 50;
        }

        return Task.Run<LoadMoreItemsResult>(
            async () =>
            {

                List<MovieInfo> result = new List<MovieInfo>();

                try
                {
                    result = await ytSearcher.SearchVideos(Query, ++CurrentPage);
                }
                catch (Exception ex) 
                {
                    // here i want to throw that exception.  
                }

                await this.dispatcher.RunAsync(
                    CoreDispatcherPriority.Normal,
                    () =>
                    {
                        foreach (MovieInfo item in result)
                            this.Add(item);
                    });

                return new LoadMoreItemsResult() { Count = (uint)result.Count() };

            }).AsAsyncOperation<LoadMoreItemsResult>();
    }

1 个答案:

答案 0 :(得分:0)

我不是Windows运行时的经验,但我会将你的代码重构为:

public Windows.Foundation.IAsyncOperation<LoadMoreItemsResult> LoadMoreItemsAsync(uint count)
{
    if (count > 50 || count <= 0)
    {
        // default load count to be set to 50
        count = 50;
    }

    return LoadMoreItemsTaskAsync(count)
        .AsAsyncOperation<LoadMoreItemsResult>();
}

private async Task<LoadMoreItemsResult> LoadMoreItemsTaskAsync(uint count)
{
    var result = await ytSearcher.SearchVideos(Query, ++CurrentPage);

    result.ForEach(i => this.Add(i));

    return new LoadMoreItemsResult() { Count = (uint)result.Count };
}

请注意List<T>具有Count属性,其中包含列表中的项目数,而Count方法是LINQ扩展方法,它迭代所有要计算的项目物品数量。

当然这不能解答您的问题,但是使用这些更清晰的代码,您可能更容易理解它或获得帮助来解决它。