Search code examples
c#multithreadingasynchronousasync-awaitcollections

Do I always need to use async/await?


I wanted to ask you about async/await. Namely, why does it always need to be used? (all my friends say so)

Example 1.

public async Task Boo()
    {
        await WriteInfoIntoFile("file.txt");

        some other logic...
    }

I have a Boo method, inside which I write something to files and then execute some logic. Asynchrony is used here so that the stream does not stop while the information is being written to the file. Everything is logical.

Example 2.

public async Task Bar()
    {
        var n = await GetNAsync(nId);
        _uow.NRepository.Remove(n);
        await _uow.CompleteAsync();
    }

But for the second example, I have a question. Why here asynchronously get the entity, if without its presence it will still be impossible to work further?


Solution

  • why does it always need to be used?

    It shouldn't always be used. Ideally (and especially for new code), it should be used for most I/O-based operations.

    Why here asynchronously get the entity, if without its presence it will still be impossible to work further?

    Asynchronous code is all about freeing up the calling thread. This brings two kinds of benefits, depending on where the code is running.

    1. If the calling thread is a UI thread inside a GUI application, then asynchrony frees up the UI thread to handle user input. In other words, the application is more responsive.
    2. If the calling thread is a server-side thread, e.g., an ASP.NET request thread, then asynchrony frees up that thread to handle other user requests. In other words, the server is able to scale further.