简体   繁体   中英

Do I need to mark all methods in the flow with async and await

I have a public method which calls multiple private methods. Do I have to mark all methods in the flow with async and await or just the method with time consuming work?

No, you don't have to mark all procedures async, only those procedures where you call other async functions. You probably do this already when calling .NET functions

async Task DoIt(...)
{
     // call async function, wait until finished
     string txt = await ReadMyTextFile();

     // call non-async function
     string reversed = txt.Reverse();

     // call async function, wait until finished
     await WriteMyTextFile(reversed);
} 

If you call an async function, you can be assured that somewhere in this function there is an await. In fact, your compiler will warn you if you forget to await somewhere inside your procedure.

If a thread that is executing the procedure meets the await, the thread won't wait idly until the awaited task is finished, but goes up its call stack to see if the caller of the procedure is not awaiting, and continues processing that procedure until is meets an await. Go up the call stack again, continue processing until the await, etc.

Task<int> ReadNumber(FileStream in
{
    // start fetching data from a database, don't await yet
    Task<int> taskFetchCustomerCount = FetchCustomerCountAsync();

    // once the await is met in FetchCustomerCountAsync, the thread will start doing this
    // also don't need the result yet. Don't await
    Task<MonthlyReport> taskReadReport = ReadMonthlyReportAsync();

    // once the await is met in ReadMonthlyReportAsync the thread will continue doing this
    // this is a non-async function
    string reportPeriod = GetReportPeriod();

    // by now, we need the result from the database. Start waiting for it
    int customerCount = await taskFetchCustomerCount;

    // if the database is not finished yet, the thread goes up the call stack to see 
    // if the caller can continue

    // after a while the database has fetched the result, we can continue
    string customerCountLine = 
        $"At the end of {reportPeriod} the company had {customerCount} customers.";

    // now we need the result from the Report reading:
    MonthlyReport report = await taskReadReport;

    // call a non-async function
    report.SetCustomerCountLine(customerCountLine);

    // save the report. Nothing to do anymore, so await until saving completed
    await report.SaveAsync();
}

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