2014-02-25 38 views
0

目前我正在開發一個地圖應用程序,它具有GridView填充滾動數據。爲此我必須實現ISupportIncrementalLoading接口。我已經做到了這一點,我的代碼工作正常。但是,如果發生異常,我想知道如何從LoadMoreItemsAsync函數中拋出Exception。以下是代碼片段。遞增加載捕獲並拋出異常Metro應用程序

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>(); 
    } 
+0

你爲什麼使用'Task.Run'? –

回答

0

我不是在Windows運行時是experient但是,我會重構代碼,以這樣的:

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擴展方法,它遍歷所有項目以計算項目數量。

當然,這並不能回答你的問題,但是使用這個更簡潔的代碼,你可能更容易弄明白,或者得到幫助。