The await operator is applied to a task in an asynchronous method to suspend the execution of the method until the awaited task completes. The task represents ongoing work.

The asynchronous method in which await is used must be modified by the async keyword. Such a method, defined by using the async modifier, and usually containing one or more await expressions, is referred to as an async method.

An async method provides a convenient way to do potentially long-running work without blocking the caller’s thread. The caller of an async method can resume its work without waiting for the async method to finish.

Example:

public async Task SampleMethod1()
{
    var result = await SampleMethodAsync();
    return "Finished";
}

public async void SampleMethod2()
{
    var result = await SampleMethodAsync();
    /* Perform some actiuon on the result*/
    Console.WriteLine(result);
}private Task

SampleMethodAsync() { //Do some time consuming action like your own service call, etc return new Task(() => null); }

In this method SampleMethodAsync returns task which does some time-consiming action. The SampleMethod1 is a asynchronous which waits for the SampleMethodAsync to complete usning the await keyword, which also returns a Task with a result as string.

In our second method SampleMethod2, we do some processing on the result obtained in this case print the result.

In both of our samples, the code written after the await keyword is executed as if its inside a completed handler i.i. after some time in a asynchronous fashion. Hence the name asynchronous method.

Tasks

Reference

Related articles

Advertisements

Share your thoughts

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s