我正在尝试使用WebClient发送POST请求,而我正在使用" UploadStringAsync"为了阻止UI冻结。我想在上传完成后返回一个变量,但是我收到一个错误:
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)
{
...
}
我收到的错误是:
因为&#39; System.Net.UploadStringCompletedEventHandler&#39;返回void,返回关键字后面不能跟一个对象表达式
答案 0 :(得分: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。