async Task
{
HttpClient client = new HttpClient();
Task
client.GetStringAsync("http://www.google.com");
string content = await getStringAsyncTask;
// control is returned to the caller
// of the DownloadFromWebAsync() method
// and resumed after getStringAsyncTask
// is completed
return content;
}
In the above DownloadFromWebAsync() method , it is first of all prefixed with the async keyword, which indicates that this method contains an asynchronous operation. This method returns a Task
async Task
Within this method, we use the HttpClient class to help us connect to the Web:
HttpClient client = new HttpClient();
In particular, the GetStringAsync() method connects to the specified URL and returns the content of the URL. It returns an object of type Task
Task
client.GetStringAsync("http://www.google.com");
Because the GetStringAsync() method could potentially take a long time, and so you need to run it asynchronously. This is achieved by using the await keyword:
string content = await getStringAsyncTask;
At this point, the GetStringAsync() method will proceed to download the specified URL and control will return to the caller of the DownloadFromWebAsync() method. All statements after this line will only be executed after the GetStringAsync() method returns.
When the GetStringAsync() method returns, the result is passed to content, and the DownloadFromWebAsync() method will now return a string.
To call the DownloadFromWebAsync() method, you would need to use the await keyword. Also, the method from which you are calling the DownloadFromWebAsync() method must also be prefixed with the async keyword, like this:
private async void button1_Click(object sender, EventArgs e)
{
string content = await DownloadFromWebAsync();
}
Task
client.GetStringAsync("http://www.google.com");
string content = await getStringAsyncTask;
string content = await
client.GetStringAsync("http://www.google.com");
I hope this simple example makes it easier for you to understand how to use the async and await keywords.
No comments:
Post a Comment