Home How and When to use `async` and `await`
Reply: 13

How and When to use `async` and `await`

Dan Dinu
1#
Dan Dinu Published in 2013-01-22 09:29:58Z

From my understanding one of the main things that async and await do is to make code easy to write and read - but is using them equal to spawning background threads to perform long duration logic?

I'm currently trying out the most basic example. I've added some comments inline. Can you clarify it for me?

// I don't understand why this method must be marked as `async`.
private async void button1_Click(object sender, EventArgs e)
{
    Task<int> access = DoSomethingAsync();
    // task independent stuff here

    // this line is reached after the 5 seconds sleep from 
    // DoSomethingAsync() method. Shouldn't it be reached immediately? 
    int a = 1; 

    // from my understanding the waiting should be done here.
    int x = await access; 
}

async Task<int> DoSomethingAsync()
{
    // is this executed on a background thread?
    System.Threading.Thread.Sleep(5000);
    return 1;
}
Druid
2#
Druid Reply to 2016-01-29 07:40:48Z

I think you've picked a bad example with System.Threading.Thread.Sleep

Point of an async Task is to let it execute in background without locking the main thread, such as doing a DownloadFileAsync

System.Threading.Thread.Sleep isn't something that is "being done", it just sleeps, and therefore your next line is reached after 5 seconds ...

Read this article, I think it is a great explanation of async and await concept: http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx

Federico Dipuma
3#
Federico Dipuma Reply to 2017-05-23 09:31:58Z

Further to the other answers, have a look at await (C# Reference)

and more specifically at the example included, it explains your situation a bit

The following Windows Forms example illustrates the use of await in an async method, WaitAsynchronouslyAsync. Contrast the behavior of that method with the behavior of WaitSynchronously. Without an await operator applied to a task, WaitSynchronously runs synchronously despite the use of the async modifier in its definition and a call to Thread.Sleep in its body.

private async void button1_Click(object sender, EventArgs e)
{
    // Call the method that runs asynchronously.
    string result = await WaitAsynchronouslyAsync();

    // Call the method that runs synchronously.
    //string result = await WaitSynchronously ();

    // Display the result.
    textBox1.Text += result;
}

// The following method runs asynchronously. The UI thread is not
// blocked during the delay. You can move or resize the Form1 window 
// while Task.Delay is running.
public async Task<string> WaitAsynchronouslyAsync()
{
    await Task.Delay(10000);
    return "Finished";
}

// The following method runs synchronously, despite the use of async.
// You cannot move or resize the Form1 window while Thread.Sleep
// is running because the UI thread is blocked.
public async Task<string> WaitSynchronously()
{
    // Add a using directive for System.Threading.
    Thread.Sleep(10000);
    return "Finished";
}
atlaste
4#
atlaste Reply to 2013-01-22 10:16:25Z

To be honest I still think the best explanation is the one about future and promises on the Wikipedia: http://en.wikipedia.org/wiki/Futures_and_promises

The basic idea is that you have a separate pool of threads that execute tasks asynchronously. When using it. The object does however make the promise that it will execute the operation at some time and give you the result when you request it. This means that it will block when you request the result and hasn't finished, but execute in the thread pool otherwise.

From there you can optimize things: some operations can be implemented async and you can optimize things like file IO and network communication by batching together subsequent requests and/or reordering them. I'm not sure if this is already in the task framework of Microsoft - but if it isn't that would be one of the first things I would add.

You can actually implement the future pattern sort-of with yields in C# 4.0. If you want to know how it works exactly, I can recommend this link that does a decent job: http://code.google.com/p/fracture/source/browse/trunk/Squared/TaskLib/ . However, if you start toying with it yourself, you will notice that you really need language support if you want to do all the cool things -- which is exactly what Microsoft did.

Cameron Tinker
5#
Cameron Tinker Reply to 2014-06-13 12:49:02Z

From my understanding one of the main things that async and await do is to make code easy to write and read.

They're to make asynchronous code easy to write and read, yes.

Is it the same thing as spawning background threads to perform long duration logic?

Not at all.

//i don't uderstand why this method must be marked as "async'.

The async keyword enables the await keyword. So any method using await must be marked async.

// this line is reached after the 5 seconds sleep from DoSomethingAsync() method. Shouldn't it be reached immediately?

No, because async methods are not run on another thread by default.

//is this executed on a background thread?

No.


You may find my async/await intro helpful. The official MSDN docs are also unusually good (particularly the TAP section), and the async team put out an excellent FAQ.

Dan Dinu
6#
Dan Dinu Reply to 2017-10-11 23:43:35Z

When using async and await the compiler generates a state machine in the background.

Here's an example on which I hope I can explain some of the high-level details that are going on:

public async Task MyMethodAsync()
{
    Task<int> longRunningTask = LongRunningOperationAsync();
    // independent work which doesn't need the result of LongRunningOperationAsync can be done here

    //and now we call await on the task 
    int result = await longRunningTask;
    //use the result 
    Console.WriteLine(result);
}

public async Task<int> LongRunningOperationAsync() // assume we return an int from this long running operation 
{
    await Task.Delay(1000); // 1 second delay
    return 1;
}

OK, so what happens here:

  1. Task<int> longRunningTask = LongRunningOperationAsync(); starts executing LongRunningOperation

  2. Independent work is done on let's assume the Main Thread (Thread ID = 1) then await longRunningTask is reached.

    Now, if the longRunningTask hasn't finished and it is still running, MyMethodAsync() will return to its calling method, thus the main thread doesn't get blocked. When the longRunningTask is done then a thread from the ThreadPool (can be any thread) will return to MyMethodAsync() in its previous context and continue execution (in this case printing the result to the console).

A second case would be that the longRunningTask has already finished its execution and the result is available. When reaching the await longRunningTask we already have the result so the code will continue executing on the very same thread. (in this case printing result to console). Of course this is not the case for the above example, where there's a Task.Delay(1000) involved.

Lex Li
7#
Lex Li Reply to 2014-09-08 02:06:42Z

This answer aims to provide some info specific to ASP.NET.

By utilizing async/await in MVC controller, it is possible to increase thread pool utilization and achieve a much better throughput, as explained in the below article,

http://www.asp.net/mvc/tutorials/mvc-4/using-asynchronous-methods-in-aspnet-mvc-4

In web applications that sees a large number of concurrent requests at start-up or has a bursty load (where concurrency increases suddenly), making these web service calls asynchronous will increase the responsiveness of your application. An asynchronous request takes the same amount of time to process as a synchronous request. For example, if a request makes a web service call that requires two seconds to complete, the request takes two seconds whether it is performed synchronously or asynchronously. However, during an asynchronous call, a thread is not blocked from responding to other requests while it waits for the first request to complete. Therefore, asynchronous requests prevent request queuing and thread pool growth when there are many concurrent requests that invoke long-running operations.

shytikov
8#
shytikov Reply to 2015-09-11 09:23:45Z

Here is a quick console program to make it clear to those who follow. The "TaskToDo" method is your long running method that you want to make async. Making it run Async is done by the TestAsync method. The test loops method just runs through the "TaskToDo" tasks and runs them Async. You can see that in the results because they don't complete in the same order from run to run - they are reporting to the console UI thread when they complete. Simplistic, but I think the simplistic examples bring out the core of the pattern better than more involved examples:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace TestingAsync
{
    class Program
    {
        static void Main(string[] args)
        {
            TestLoops();
            Console.Read();
        }

        private static async void TestLoops()
        {
            for (int i = 0; i < 100; i++)
            {
                await TestAsync(i);
            }
        }

        private static Task TestAsync(int i)
        {
            return Task.Run(() => TaskToDo(i));
        }

        private async static void TaskToDo(int i)
        {
            await Task.Delay(10);
            Console.WriteLine(i);
        }
    }
}
sppc42
9#
sppc42 Reply to 2015-08-13 09:32:13Z

Showing the above explanations in action in a simple console program -

class Program
{
    static void Main(string[] args)
    {
        TestAsyncAwaitMethods();
        Console.WriteLine("Press any key to exit...");
        Console.ReadLine();
    }

    public async static void TestAsyncAwaitMethods()
    {
        await LongRunningMethod();
    }

    public static async Task<int> LongRunningMethod()
    {
        Console.WriteLine("Starting Long Running method...");
        await Task.Delay(5000);
        Console.WriteLine("End Long Running method...");
        return 1;
    }
}

And the output is:

Starting Long Running method...
Press any key to exit...
End Long Running method...

Thus,

  1. Main starts the long running method via TestAsyncAwaitMethods. That immediately returns without halting the current thread and we immediately see 'Press any key to exit' message
  2. All this while, the LongRunningMethod is running in the background. Once its completed, another thread from Threadpool picks up this context and displays the final message

Thus, not thread is blocked.

Dmitry G.
10#
Dmitry G. Reply to 2016-10-04 16:16:30Z

is using them equal to spawning background threads to perform long duration logic?

This article MDSN:Asynchronous Programming with async and await (C#) explains it explicitly:

The async and await keywords don't cause additional threads to be created. Async methods don't require multithreading because an async method doesn't run on its own thread. The method runs on the current synchronization context and uses time on the thread only when the method is active.

Joe Phillips
11#
Joe Phillips Reply to 2017-11-10 17:02:10Z

I've struggled to find simple examples of what async/await actually does. Once I finally started to understand, I created this simple little example which I think provides a very good general idea of what's going on when using async/await at a high level.

Note: Task.Delay(1000) simply blocks for 1 second

Console.WriteLine(DateTime.Now);

// This block takes 1 second to run because all
// 5 tasks are running simultaneously
{
    var a = Task.Delay(1000);
    var b = Task.Delay(1000);
    var c = Task.Delay(1000);
    var d = Task.Delay(1000);
    var e = Task.Delay(1000);

    await a;
    await b;
    await c;
    await d;
    await e;
}

Console.WriteLine(DateTime.Now);

// This block takes 5 seconds to run because each "await"
// pauses the program until the task finishes
{
    await Task.Delay(1000);
    await Task.Delay(1000);
    await Task.Delay(1000);
    await Task.Delay(1000);
    await Task.Delay(1000);
}
Console.WriteLine(DateTime.Now);

OUTPUT:

5/24/2017 2:22:50 PM
5/24/2017 2:22:51 PM (First block took 1 second)
5/24/2017 2:22:56 PM (Second block took 5 seconds)
user21306
12#
user21306 Reply to 2017-06-02 21:15:25Z

The way I understand it is also, there should be a third term added to the mix: Task.

Async is just a qualifier you put on your method to say it's an asynchronous method.

Task is the return of the async function. It executes asynchronously.

You await a Task. When code execution reaches this line, control jumps out back to caller of your surrounding original function.

If instead, you assign the return of an async function (ie Task) to a variable, when code execution reaches this line, it just continues past that line in the surrounding function while the Task executes asynchronously.

Tone Škoda
13#
Tone Škoda Reply to 2017-07-15 08:03:51Z

All the answers here use Task.Delay() or some other built in async function. But here is my example that use none of those async functions:

    // Starts counting to a large numbewr and then immediately displays message "i'm counting...". 
    // Then it waits for task to finish and displays "finished, press any key".
    static void asyncTest ()
    {
        Console.WriteLine("Started asyncTest()");
        Task<long> task = asyncTest_count();
        Console.WriteLine("Started counting, please wait...");
        task.Wait(); // if you comment this line you will see that message "Finished counting" will be displayed before we actually finished counting.
        //Console.WriteLine("Finished counting to " + task.Result.ToString()); // using task.Result seems to also call task.Wait().
        Console.WriteLine("Finished counting.");
        Console.WriteLine("Press any key to exit program.");
        Console.ReadLine();
    }

    static async Task<long> asyncTest_count()
    {
        long k = 0;
        Console.WriteLine("Started asyncTest_count()");
        await Task.Run(() =>
        {
            long countTo = 100000000;
            int prevPercentDone = -1;
            for (long i = 0; i <= countTo; i++)
            {
                int percentDone = (int)(100 * (i / (double)countTo));
                if (percentDone != prevPercentDone)
                {
                    prevPercentDone = percentDone;
                    Console.Write(percentDone.ToString() + "% ");
                }

                k = i;
            }
        });
        Console.WriteLine("");
        Console.WriteLine("Finished asyncTest_count()");
        return k;
    }
lazydeveloper
14#
lazydeveloper Reply to 2017-08-31 18:40:12Z

In the following code, the HttpClient method GetByteArrayAsync returns a Task, getContentsTask. The task is a promise to produce the actual byte array when the task is complete. The await operator is applied to getContentsTask to suspend execution in SumPageSizesAsync until getContentsTask is complete. In the meantime, control is returned to the caller of SumPageSizesAsync. When getContentsTask is finished, the await expression evaluates to a byte array.

private async Task SumPageSizesAsync()
{
    // To use the HttpClient type in desktop apps, you must include a using directive and add a 
    // reference for the System.Net.Http namespace.
    HttpClient client = new HttpClient();
    // . . .
    Task<byte[]> getContentsTask = client.GetByteArrayAsync(url);
    byte[] urlContents = await getContentsTask;

    // Equivalently, now that you see how it works, you can write the same thing in a single line.
    //byte[] urlContents = await client.GetByteArrayAsync(url);
    // . . .
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.370563 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO