[英]Async CTP method freeze when return value
我試圖創建一個返回值的異步方法。 使用方法而不返回時一切正常。 您可以處理數據,但添加return子句時會出現問題。 程序完全凍結沒有任何錯誤或一段時間。
請看代碼:
public void runTheAsync(){
string resp = sendRequest("http://google.com","x=y").Result;
}
public async Task<string> sendRequest(string url, string postdata)
{
//There is no problem if you use void as the return value , the problem appears when Task<string> used. the program fully go to freeze.
Console.WriteLine("On the UI thread.");
string result = await TaskEx.Run(() =>
{
Console.WriteLine("Starting CPU-intensive work on background thread...");
string work = webRequest(url,postdata);
return work;
});
return result;
}
public string webRequest(string url, string postdata)
{
string _return = "";
WebClient client = new WebClient();
byte[] data = Encoding.UTF8.GetBytes(postdata);
Uri uri = new Uri(url);
_return = System.Text.Encoding.UTF8.GetString(client.UploadData(uri, "POST", data));
return _return;
}
string resp = sendRequest("http://google.com","x=y").Result;
那是你的問題。 如果在Task
上調用Result
,它將一直阻塞,直到Task
完成。
相反,你可以這樣做:
public async void runTheAsync()
{
string resp = await sendRequest("http://google.com","x=y");
}
但是應該避免創建async void
方法。 你是否真的可以避免它,取決於你如何稱呼它。
試試這個,數據正確性檢查等省略但你忽略它們:-):
public async Task<string> UploadRequestAsync(string url, string postdata)
{
string result = await Encoding.GetString(
new WebClient().UploadData(new Uri(uri), "POST", Encoding.UTF8.GetBytes(postdata)));
return result;
}
你以某種方式做了兩次工作, await
明確啟動的任務。 我很想知道生成的代碼是什么樣的......當然,在生產代碼中使用.NET 4.5中的適當類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.