async await

async-await is a very important concept from C#. It allows you to execute code in another thread than from the calling one; this results in a responsive UI even while  long background tasks are running.

Some examples:

/* ## Example 1 ## */
public async Task<bool> Execute()
{
    //long running CPU bound operation
    await Task.Run(() => {
    for (int i = 0; i != 10000000; ++i)
        ;
    });

    //long running I/O Operation
    using (var client = new HttpClient())
    {
        await client.GetStringAsync(url);
    }
    return true;
}

//call this method
var response = await Execute();

/* ## Example 2 ## */
//remove the async-await if not needed, and return directly the Task.
public Task<string> Execute2()
{
    //long running I/O Operation
    using (var client = new HttpClient())
    {
        return client.GetStringAsync(url);
    }
}

//call this method
var response = await Execute2();

/* ## Example 3 ## */
//add the async keyword to event handlers to use them asynchronusly
public async void OnTapped()
{
    //long running I/O Operation
    using (var client = new HttpClient())
    {
        await client.GetStringAsync(url);
    }
}

From my own experiences, the simpler the expressions, the better. If it looks wrong or overcomplicated to you, it probably is. I recommend to take a look at Stephen Cleary’s Blog (specifically at async-await) for extensive information and tutorials about async-await.

Leave a Reply

Your email address will not be published. Required fields are marked *