2016-12-16 28 views
0

我試圖使用WebClient發送POST請求,並且我正在使用「UploadStringAsync」來阻止UI凍結。我要上傳完成後返回一個變量,但我得到了一個錯誤:在uploadstring上返回一個變量完成

try 
{ 
    List<string> results = new List<string>(); 

    //Contact the API 
    using (WebClient getResults = new WebClient()) 
    { 

    ... 

     //Send the POST and get the result! 

     getResults.UploadStringCompleted += (sender, e) => 
     { 
      dynamic finalResult = JObject.Parse(e.Result);//finalResults.selectedProfile.name 
      results.Add(finalResult.selectedProfile.name); 
      return (results.toArray()); //Error is here 
     }; 

     getResults.UploadStringAsync(new Uri(URL), "POST", postInfo); 
    } 

    //This is what was there before: return (results.ToArray()); 
} 
catch (Exception ex) 
{ 
    ... 
} 

我收到的錯誤是:

Since 'System.Net.UploadStringCompletedEventHandler' returns void, a return keyword must not be followed by an object expression

+0

你爲什麼不寫一個函數,它需要你的數組作爲參數,並在你的處理程序結束時調用它? – Brutus

回答

0

如果你想使用一些異步結構,我希望首先你必須寫如下的asyn函數。

static async Task<string> GetData() 
    { 
     using (WebClient webClient = new WebClient()) 
     { 
      return await webClient.UploadStringTaskAsync(new Uri("http://www.facebook.com/"), "POST", string.Empty); 
     } 
    } 

然後你可以等待結果和解析。

Task<string> getDataTask = GetData(); 
    if (!string.IsNullOrEmpty(getDataTask.Result)) 
    { 
     List<string> results = new List<string>(); 
     dynamic finalResult = JObject.Parse(getDataTask.Result); 
     results.Add(finalResult.selectedProfile.name); 
    } 

不過,我想的是,當我們處理UI凍結,例如在WPF應用程序,我們應該使用多線程,但沒有ASYC。