2012-12-16 77 views
0

我想製作Twitter輿情分析Windows Phone應用程序。發送多個請求到API時,webclient發生I/O錯誤

該應用程序的工作原理是根據用戶輸入的查詢條件檢索所有相關的推文。例如,如果我在輸入搜索框中輸入「Windows Phone」,結果將顯示包含「windows phone」條款的所有推文。

這裏的代碼(即我從Arik Poznanski's Blog獲得)

/// <summary> 
    /// Searches the specified search text. 
    /// </summary> 
    /// <param name="searchText">The search text.</param> 
    /// <param name="onSearchCompleted">The on search completed.</param> 
    /// <param name="onError">The on error.</param> 
    public static void Search(string searchText, Action<IEnumerable<Twit>> onSearchCompleted = null, Action<Exception> onError = null, Action onFinally = null) 
    { 
     WebClient webClient = new WebClient(); 

     // register on download complete event 
     webClient.OpenReadCompleted += delegate(object sender, OpenReadCompletedEventArgs e) 
     { 
      try 
      { 
       // report error 
       if (e.Error != null) 
       { 
        if (onError != null) 
        { 
         onError(e.Error); 
        } 
        return; 
       } 

       // convert json result to model 
       Stream stream = e.Result; 
       DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(TwitterResults)); 
       TwitterResults twitterResults = (TwitterResults)dataContractJsonSerializer.ReadObject(stream); 

       App thisApp = Application.Current as App; 
       thisApp.klasifikasi = new Klasifikasi(); 

       foreach (Twit Tweet in twitterResults.results) 
       { 
        try 
        { 
         thisApp.klasifikasi.UploadData(Tweet); //requesting 
         break; 
        } 
        finally 
        { 
         // notify finally callback 
         if (onFinally != null) 
         { 
          onFinally(); 
         } 
        } 
       } 
       //thisApp.klasifikasi.UploadDatas(twitterResults.results); 
       //thisApp.PositiveTweetModel = new PositiveTweetModel("Positive", twitterResults.results); 

       // notify completed callback 
       if (onSearchCompleted != null) 
       { 
        onSearchCompleted(twitterResults.results); 

        /// Divide the list here 

       } 
      } 
      finally 
      { 
       // notify finally callback 
       if (onFinally != null) 
       { 
        onFinally(); 
       } 
      } 
     }; 

     string encodedSearchText = HttpUtility.UrlEncode(searchText); 
     webClient.OpenReadAsync(new Uri(string.Format(TwitterSearchQuery, encodedSearchText))); 
    } 

,並調用該方法

  TwitterService.Search(
      text, 
      (items) => { PositiveList.ItemsSource = items; }, 
      (exception) => { MessageBox.Show(exception.Message); }, 
      null 
      ); 

到POST數據上傳到API

public void UploadData(Twit tweetPerSend) 
    { 
     if (NetworkInterface.GetIsNetworkAvailable()) 
     { 
      chatterbox.Headers[HttpRequestHeader.ContentType] = "application/x-www-      form-urlencoded"; 
      chatterbox.Headers["X-Mashape-Authorization"] = "MXBxYmptdjhlbzVnanJnYndicXNpN2NwdWlvMWE1OjA0YTljMWJjMDg4MzVkYWY2YmIzMzczZWFkNDlmYWRkNDYzNGU5NmI="; 

      var Uri = new Uri("https://chatterboxco-sentiment-analysis-for-social-media---nokia.p.mashape.com/sentiment/current/classify_text/"); 

      StringBuilder postData = new StringBuilder(); 
      postData.AppendFormat("{0}={1}", "lang", HttpUtility.UrlEncode("en")); 
      postData.AppendFormat("&{0}={1}", "text", HttpUtility.UrlEncode(tweetPerSend.DecodedText)); 
      postData.AppendFormat("&{0}={1}", "exclude", HttpUtility.UrlEncode("is")); // disesuaikan 
      postData.AppendFormat("&{0}={1}", "detectlang", HttpUtility.UrlEncode("0")); 
      chatterbox.UploadStringAsync(Uri, "POST", postData.ToString()); 
      chatterbox.UploadStringCompleted += new UploadStringCompletedEventHandler(chatterbox_UploadStringCompleted); 

     } 
    } 


    void chatterbox_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e) 
    { 
     var chatterbox = sender as WebClient; 
     chatterbox.UploadStringCompleted -= chatterbox_UploadStringCompleted; 
     string response = string.Empty; 
     if (!e.Cancelled) 
     { 
      response = HttpUtility.UrlDecode(e.Result); 
      nilaiKlasifikasi = ParsingHasil(response); 
      MessageBox.Show(nilaiKlasifikasi.ToString()); //just testing 
      //textBlock1.Text = response; 
     } 
    } 

    private double ParsingHasil(String response) 
    { 

     var result = Regex.Match(@response, @"(?<=""value"":)(-?\d+(\.\d+)?)(?=,|$)"); 
     Debug.WriteLine(result); 
     double hasil = Convert.ToDouble(result.ToString()); 
     //return Convert.ToInt32(result); 
     return hasil; 

    } 

然而,不僅僅是1個鳴叫來檢索,會有很多鳴叫,所以主要的問題是,我檢索後所有的鳴叫和請求結果的API,我得到這個錯誤「WebClient不支持併發I/O操作」

有誰知道如何解決這個問題?

任何幫助,將不勝感激

+0

在你得到了什麼線這個錯誤/異常 –

+0

@PeterRitchie:?在這行「話匣子.UploadStringAsync(Uri,「POST」,postData.ToString());' – sheldon90

回答

1

你必須在一次執行UploadStringAsync同步之一。在UploadStringCompleted處理下一UploadStringAsync(即鏈執行

或者,爲每個UploadStringAsync一個新的Web客戶端

+0

我調試代碼後,我意識到,這個方法掛鉤請求api 'foreach(Twit Tweet in twitterResults.results) thisApp。 klasifikasi.UploadData(鳴叫); //請求' ,持續點火雖然過去的過程尚未完成.. 如何解決這個問題? – sheldon90

+0

正如我的回答詳細說明的那樣,在調用下一個UploadData之前,您必須等待UploadStringCompleted處理程序被調用。 –

+0

如何知道UploadStringCompleted是否被調用/完成? – sheldon90

相關問題