简体   繁体   中英

When I use await in an async method why does it not skip that so it can work in the background and go to the following lines?

I have the following code:

protected override async void OnStart() {
   await Helper.PopulateMetrics();
   await Helper.LogStart();
   if (Settings.Rev == REV.No && (new[] { 15, 30, 50 }).Contains(Settings.Trk2))

I guess I am confused as when I set a breakpoint in await Helper.LogStart() I see that breakpoint his before the line starting with "if (Settings ... "

as there is an await should the code after those not be hit first?

Here's what the LogStart() method looks like:

 public static async Task LogStart()
 {
     // code
     await App.CDB.InsertLogItem(logStart);
 }

Ideally I would like these two methods to just run in the background one after the other while the code immediately skips them.

The await keyword causes the execution to wait until the Helper.LogStart() function has completed. If you want to continue executing, you can store the returned Task object into another variable and await on it later:

var task = Helper.LogStart();
/* something else */
await task;

When we use await that does not means it skip that code and run in background. When we have await at that place new child thread would be created and that new thread will handle execution of PopularMatrics() but Main thread will wait until child thread finished its job.

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