Per*_*est 2 .net c# asynchronous async-await
我正在尝试学习C#中的机制async和await机制.
在最简单的例子我很清楚.
这条线
Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");
Run Code Online (Sandbox Code Playgroud)
触发异步Web调用.控件返回AccessTheWebAsync().它是免费的DoIndependentWork().这样做了以后它等待任务的完成getStringTask,当这个结果可在函数执行的下一行
return urlContents.Length;
所以,据我了解的目的async呼叫,让呼叫者执行其他操作时,标签的操作与async在进展.
但是,在这个函数中,我对这个例子有点困惑.
private async Task<byte[]> GetURLContentsAsync(string url)
{
// The downloaded resource ends up in the variable named content.
var content = new MemoryStream();
// Initialize an HttpWebRequest for the current URL.
var webReq = (HttpWebRequest)WebRequest.Create(url);
// Send the request to the Internet resource and wait for
// the response.
using (WebResponse response = await webReq.GetResponseAsync())
// The previous statement abbreviates the following two statements.
//Task<WebResponse> responseTask = webReq.GetResponseAsync();
//using (WebResponse response = await responseTask)
{
// Get the data stream that is associated with the specified url.
using (Stream responseStream = response.GetResponseStream())
{
// Read the bytes in responseStream and copy them to content.
await responseStream.CopyToAsync(content);
// The previous statement abbreviates the following two statements.
// CopyToAsync returns a Task, not a Task<T>.
//Task copyTask = responseStream.CopyToAsync(content);
// When copyTask is completed, content contains a copy of
// responseStream.
//await copyTask;
}
}
// Return the result as a byte array.
return content.ToArray();
}
Run Code Online (Sandbox Code Playgroud)
在方法内部GetURLContentsAsync(),有两个异步调用.但是,API会同时await调用两者.调用者在操作的触发器和数据的接收之间没有做任何事情async.所以,据我所知,这个async/await机制在这里没有任何好处.我错过了一些明显的东西吗?
您的代码不需要在await'd异步调用之间明确地执行任何操作以获得收益.这意味着线程没有等待每个调用完成,它可以做其他工作.
如果这是一个Web应用程序,则可能导致处理更多请求.如果它是Windows应用程序,则意味着UI线程未被阻止,并且用户具有更好的体验.