3
我已經寫了下面兩種方法差異返回任務和異步任務
private Task<string> GetStringTask(string url)
{
var client = new WebClient();
var task = client.DownloadDataTaskAsync(new Uri(url));
var task2 = task.ContinueWith<string>(task1 =>
{
var str = Encoding.Default.GetString(task1.Result);
Thread.Sleep(5000);
return str;
});
return task2;
}
private async Task<string> GetStringAsyc(string url)
{
var client = new WebClient();
var htmlByte = await client.DownloadDataTaskAsync(new Uri(url));
var task2 = await Task.Factory.StartNew(() =>
{
var str = Encoding.Default.GetString(htmlByte);
Thread.Sleep(2000);
return str;
});
return task2;
}
我可以調用另一個異步方法相同的方式裏面的兩種方法,如下面
var mystring = await GetStringTask("http://www.microsoft.com");
var mystring1 = await GetStringAsync("http://www.microsoft.com");
兩個方法回相同的結果。任何人都可以解釋這兩種方法之間的區別。
看看這個。 http://stackoverflow.com/questions/22997523/difference-between-task-and-async –