-1

I've reviewed async and await in C# in some detail in the past, including reviewing all of the StackOverflow questions I've found on the topic, however I have never implemented async and await in code, for the following reasons:

  • My understanding of the main performance benefit is if you have a long running process, followed by logic that is time-consuming to perform, followed by consumption of something returned by the first long-running process. I've never encountered this scenario. I've encountered scenarios where there is minimal logic between an initial long running process and something that relies on the long running process, and it's not compelling enough to introduce await and async for a minor performance saving. Introducing an async call introduces a small degree of complexity in terms of the order of execution, and for small performance gains I've always felt that this complexity isn't worth it
  • It only makes async code easier to write, and I'm usually doing all my async stuff with JavaScript (typically Angular) at the front-end, so I've never recognised a compelling need for async work at the back end

I'm often asked at job interviews about my understanding of async and await, and I can answer the question OK, however I've never fully comprehended or witnessed a case where async and await is a clearly preferable pattern in a piece of code. As I'm not in the habit of using async and await, I want to be able to recognise when a use case or scenario is calling out for the use of async and await. What is a good practical example of a compelling use case or scenario that is commonly implemented in a system?

Chris Halcrow
  • 28,994
  • 18
  • 176
  • 206
  • 4
    Asynchronous IO comes to mind. – David Haim Jul 25 '18 at 23:34
  • Being able to asynchronously handle requests in web servers is probably reason #1. But that's summed up as asynchronous IO as it was mentioned – Camilo Terevinto Jul 25 '18 at 23:36
  • 1
    https://stackoverflow.com/questions/31185072/effectively-use-async-await-with-asp-net-web-api https://stackoverflow.com/questions/25716366/c-sharp-await-async-in-webapi-whats-the-point https://stackoverflow.com/questions/37877803/use-of-async-await-in-console-or-web-apps https://stackoverflow.com/questions/17985726/when-do-you-really-need-async-on-a-web-framework may be worth a read. `and for small performance gains I've always felt that this complexity isn't worth it` In some contexts (like large scale websites) it can definitely be worth it. – mjwills Jul 25 '18 at 23:44
  • 1
    We must have read something completely different... How is asking for real-world scenarios "borderline" asking for validation of a predisposed opinion? – ForeverZer0 Jul 26 '18 at 02:57
  • Thanks @bommelding, however on reading https://en.wikipedia.org/wiki/Asynchronous_I/O the definition of asynchronous IO supports that my understanding of the performance benefit is correct. – Chris Halcrow Jul 26 '18 at 22:44

3 Answers3

2

A good example would be saving data to a file, or to a database.

Here's an example:

    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        string StartDirectory = @"c:\Users\exampleuser\start";
        string EndDirectory = @"c:\Users\exampleuser\end";

        foreach (string filename in Directory.EnumerateFiles(StartDirectory))
        {
            using (FileStream SourceStream = File.Open(filename, FileMode.Open))
            {
                using (FileStream DestinationStream = File.Create(EndDirectory + filename.Substring(filename.LastIndexOf('\\'))))
                {
                    await SourceStream.CopyToAsync(DestinationStream);
                }
            }
        }
    }

implemented directly from Microsoft: https://learn.microsoft.com/en-us/dotnet/standard/io/asynchronous-file-i-o

0

Well I think what people seem to be forgetting here is that async I/O when used with I/O completion ports (IOCP) that async/await nicely encapsulates, does not use an expensive thread thus allowing you to perform more I/O operations per second with minimal threading overhead. See There Is No Thread

Pure overlapped I/O though asynchronous, does require a thread to wait on a Windows file handle thus making it not as efficient as IOCP.

All I/O is by nature async, synchronous methods like Stream.Read() are a cop out

That's incorrect. There is also blocking I/O. You soon know you are using blocking I/O because your thread usage skyrockets. e.g. blocking I/O for network I/O operations in the HAPIHL7 .NET library.

  • There is no blocking I/O. Only APIs that block a thread while waiting for the callback. – H H Jul 29 '18 at 19:41
  • @HenkHolterman You are in error. Deep down, `FILE_FLAG_OVERLAPPED` is optional not compulsory. There is nothing an app from using excessive synchronous calls with a tiny buffer thus causing high CPU load. _"[A synchronous handle behaves such that I/O function calls using that handle are blocked until they complete, while an asynchronous file handle makes it possible for the system to return immediately from I/O function calls](https://learn.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-createfilea)"_. **Again, I tell you this was the case in the .NET library HAPIHL7** –  Jul 30 '18 at 00:21
  • @HenkHolterman this was even a problem back in the day with inefficient serial comms using software flow control over hardware flow control - it put too much strain on the CPU and limited the upper throughput –  Jul 30 '18 at 00:25
-2

Thanks @David Haim for the prompt to read up on Asyncronous IO - https://en.wikipedia.org/wiki/Asynchronous_I/O. The point is that in a system where an operation will be carried out many times, then it's important to calculate that there can be a significant cumulative performance improvement of async/await (even if it's only generating small performance increases at a method level)

The project I'm currently working on is a very good example of where there is a requirement for implementingasync/await. The system communicates with environmental measurement devices (e.g. weather monitoring instruments), that are attached direct to a PC, to be regularly polled at frequent intervals. As this polling is intensive and can be high-volume, the performance savings of carrying on with any operations that aren't dependent on the returned data, (particularly during consumption of polled values) add up significantly. Strictly speaking this type of polling in a system infers the need for parallelism and may require performance considerations in addition to using async and await operations.

In general, any real-time data polling that is high volume and/or high frequency probably constitutes a compelling use case for async/await somewhere in the code.

Chris Halcrow
  • 28,994
  • 18
  • 176
  • 206