Use Journals for your notes and blogging!

Software Development

A journal for sharing all things software development related


Async

Wed, 08 Jan 2020 13:22 UTC by garethbrown

Basic

https://docs.microsoft.com/en-us/dotnet/csharp/async

In Depth

https://docs.microsoft.com/en-us/dotnet/standard/async-in-depth

The key takeaway is that await causes code to "yeild" to the caller - rather than being thought of strictly as blocking ...

For I/O bound - code does not run on a separate thread, rather it starts and completes asyncronously.

It’s important to reason about tasks as abstractions of work happening asynchronously, and not an abstraction over threading. By default, tasks execute on the current thread and delegate work to the Operating System, as appropriate. Optionally, tasks can be explicitly requested to run on a separate thread via the Task.Run API.

If you do want work to happen in a different thread, that is where Task.Run comes in (described along with CPU bound work in the basic doc)

Example

public Task<string> GetHtmlAsync()
{
    // Execution is synchronous here
    var client = new HttpClient();

    return client.GetStringAsync("https://www.dotnetfoundation.org");
}

Why is async better than threads

This model works well with a typical server scenario workload. Because there are no threads dedicated to blocking on unfinished tasks, the server threadpool can service a much higher volume of web requests.

...

Although this is a contrived example, it works in a very similar fashion in the real world. In fact, you can expect a server to be able to handle an order of magnitude more requests using async and await than if it were dedicating a thread for each request it receives.


The information on this site is provided “AS IS” and without warranties of any kind either express or implied. To the fullest extent permissible pursuant to applicable laws, the author disclaims all warranties, express or implied, including, but not limited to, implied warranties of merchantability, non-infringement and suitability for a particular purpose.


Software development notes and articles

Email garethbrown: mail@appsoftware.com

UI block loader
One moment please ...