2015-12-30 40 views
0

我試圖在VS中創建一個Winforms應用程序來搜索特定的關鍵字,並檢索我的應用程序中的推文顯示。 下面是我的代碼,試圖從我的個人資料得到100鳴叫,並在我的窗體構造函數的新方法的調用,然後將數據向主鳴叫列表框中的分配我的形式使用LINQ to Twitter訪問twitter C#使用LINQ to Twitter

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.Text.RegularExpressions; 
using LinqToTwitter; 

    public partial class Form1 : Form 
     { 
      private SingleUserAuthorizer authorizer = 
      new SingleUserAuthorizer 
      { 
       CredentialStore = new 
       SingleUserInMemoryCredentialStore 
       { 
        ConsumerKey ="", 
        ConsumerSecret ="", 
        AccessToken ="", 
        AccessTokenSecret ="" 
       } 
      }; 

      private List<Status> currentTweets; 
      public Form1() 
      { 
       InitializeComponent(); 

       GetMostRecent100HomeTimeLine(); 
       lstTweetList.Items.Clear(); 
       currentTweets.ForEach(tweet => 
        lstTweetList.Items.Add(tweet.Text)); 
      } 
      private void GetMostRecent100HomeTimeLine() 
      { 
       var twitterContext = new TwitterContext(authorizer); 

       var tweets = from tweet in twitterContext.Status 
          where tweet.Type == StatusType.Home && 
          tweet.Count == 100 
          select tweet; 

       currentTweets = tweets.ToList(); 
      } 

[類型「System.AggregateException」未處理的異常出現在mscorlib.dll]是裏面的代碼發生以下

currentTweets = tweets.ToList(); 

我的猜測是它的LinqToTwitter庫試圖枚舉「鳴叫」的收集和發現有或者沒有數據,或者無法檢索數據。 我是這個主題的初學者,這是我的項目。

希望有人能指導我

+0

請爲您的問題添加一個內部異常類型和文本。 –

+0

您的where語句中的&& tweet.Count == 100'子句看起來不正確。這隻會在「Count」爲100時選擇一條推文。當然,情況並非總是如此。如果你把它拿出來會發生什麼? – ChrisF

+0

仍會發生同樣的問題 – KingsleyChoo

回答

0

LINQ來解決問題,以Twitter是異步。所以你應該在代碼中使用asyncawait關鍵字。這也意味着將查詢放入構造函數中並不是一個好主意。在這種情況下,我會使用Form.Load事件。假設,你迷上了一個Form1_Load處理器的Form1Load事件,你可以重新寫這樣的代碼:

 public async void Form1_Load() 
     { 
      await GetMostRecent100HomeTimeLine(); 
      lstTweetList.Items.Clear(); 
      currentTweets.ForEach(tweet => 
       lstTweetList.Items.Add(tweet.Text)); 
     } 
     private async Task GetMostRecent100HomeTimeLine() 
     { 
      var twitterContext = new TwitterContext(authorizer); 

      var tweets = from tweet in twitterContext.Status 
         where tweet.Type == StatusType.Home && 
         tweet.Count == 100 
         select tweet; 

      currentTweets = await tweets.ToListAsync(); 
     } 

注意,Form1_Load方法是async。它還返回void,這是必要的,應該只用於頂級異步事件處理程序。它awaitsGetMostRecent100HomeTimeLine返回的任務。

GetMostRecent100HomeTimeLine方法也是async,但返回Task。在初始的async void事件處理程序下面的異步調用鏈中的所有方法應該返回TaskTask<T>。這可以讓你的await他們的任務,使調用方法不會在被調用的方法完成之前返回。

最後,請注意代碼awaitsToListAsync返回的任務。雖然編譯器允許您使用ToList(不需要等待),但它在運行時不起作用,因爲LINQ to Twitter是異步的,並期望您等待它的運算符,如ToListAsyncSingleOrDefaultAsyncFirstOrDefaultAsync

您還可以使用try/catch處理程序來捕獲拋出的任何異常。 LINQ to Twitter包含TwitterQueryException中的大多數異常,這些異常將包含來自Twitter API的任何錯誤消息和相關代碼。