简体   繁体   中英

Not sure where to use an await operator in an async method

After reading lot of stuff about async/await, I still not sure where do I use await operator in my async method:

    public async Task<IActionResult> DailySchedule(int professionalId, DateTime date)
    {
        var professional = professionalServices.Find(professionalId);            
        var appointments = scheduleService.SearchForAppointments(date, professional);
        appointments = scheduleService.SomeCalculation(appointments);

        return PartialView(appointments);
    }

Should I create an async version for all 3 method and call like this?

        var professional = await professionalServices.FindAsync(professionalId);            
        var appointments = await scheduleService.SearchForAppointmentsAsync(date, professional);
        appointments = await scheduleService.SomeCalculationAsync(appointments);

or Should I make async only the first one ?

        var professional = await professionalServices.FindAsync(professionalId);            
        var appointments = scheduleService.SearchForAppointments(date, professional);
        appointments = scheduleService.SomeCalculation(appointments);

What´s is the difference?

I still not sure where do I use await operator in my async method

You're approaching the problem from the wrong end.

The first thing to change when converting to async is the lowest-level API calls . There are some operations that are naturally asynchronous - specifically, I/O operations. Other operations are naturally synchronous - eg, CPU code.

Based on the names "Find", "SearchForAppointments, and "SomeCalculation", I'd suspect that Find and SearchForAppointments are I/O-based, possibly hitting a database, while SomeCalculation is just doing some CPU calculation.

But don't change Find to FindAsync just yet. That's still going the wrong way. The right way is to start at the lowest API, so whatever I/O that Find eventually does. For example, if this is an EF query, then use the EF6 asynchronous methods within Find . Then Find should become FindAsync , which should drive DailySchedule to be DailyScheduleAsync , which causes its callers to become async, etc. That's the way that async should grow.

Every async method call needs to be await ed, so that every method call releases the thread and thus not causing a block. Therefore in your case this is how you should do it:

var professional = await professionalServices.FindAsync(professionalId);            
var appointments = await scheduleService.SearchForAppointmentsasync(date, professional);
appointments = await scheduleService.SomeCalculationAsync(appointments);

As VSG24 has said, you should await each and every call that can be awaited that is because this will help you keep the main thread free from any long running task — that are for instance, tasks that download data from internet, tasks that save the data to the disk using I/O etc. The problem was that whenever you had to do a long running task, it always froze the UI. To overcome this, asynchronous pattern was used and thus this async/await allows you create a function that does the long running task on the background and your main thread keeps talking to the users .

I still not sure where do I use await operator in my async method

The intuition is that every function ending with Async can be awaited (provided their signature also matches, the following) and that they return either a Task , or Task<T> . Then they can be awaited using a function that returns void — you cannot await void . So the functions where there will be a bit longer to respond, you should apply await there. My own opinion is that a function that might take more than 1 second should be awaited — because that is a 1 second on your device, maybe your client has to wait for 5 seconds, or worse 10 seconds. They are just going to close the application and walk away saying, It doesn't work! .

Ok, if one of these is very very fast, it does not need to be async, right ?

Fast in what manner? Don't forget that your clients may not have very very fast machines and they are definitely going to suffer from the frozen applications. So them a favor and always await the functions.

What´s is the difference?

The difference is that in the last code sample, only the first call will be awaited and the others will execute synchronously. Visual Studio will also explain this part to you by providing green squiggly lines under the code that you can see by hovering over it. That is why, you should await every async call where possible.

Tip : If the process in the function is required, such as loading all of the data before starting the application then you should avoid async/await pattern and instead use the synchronous approach to download the data and perform other tasks. So it entirely depends on what you are doing instead of what the document says. :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM