async await

suggest change

The await keyword was added in C# 5.0, supported from Visual Studio 2012 onward. It builds on the Task Parallel Library (TPL). await pauses the method until the awaited task has completed and its result is available. A method that uses await must be marked async, unless it returns a task directly as shown later.

Using async with void is strongly discouraged. For more info you can look here.

Example:

public async Task DoSomethingAsync()
{    
    Console.WriteLine("Starting a useless process...");
    Stopwatch stopwatch = Stopwatch.StartNew();
    int delay = await UselessProcessAsync(1000);
    stopwatch.Stop();
    Console.WriteLine("A useless process took {0} milliseconds to execute.", stopwatch.ElapsedMilliseconds);
}

public async Task<int> UselessProcessAsync(int x)
{
    await Task.Delay(x);
    return x;
}

Output:

“Starting a useless process…“ … 1 second delay… “A useless process took 1000 milliseconds to execute.”

The keyword pairs async and await can be omitted if a Task or Task<T> returning method only returns a single asynchronous operation.

Rather than this:

public async Task PrintAndDelayAsync(string message, int delay)
{
    Debug.WriteLine(message);
    await Task.Delay(delay);
}

It is preferred to do this:

public Task PrintAndDelayAsync(string message, int delay)
{
    Debug.WriteLine(message);
    return Task.Delay(delay);
}

In C# 5.0 await cannot be used in catch and finally.

With C# 6.0 await can be used in catch and finally.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents