Home > Net >  C# If I run 2 async commands one after the other, can I guarantee the first will always run before t
C# If I run 2 async commands one after the other, can I guarantee the first will always run before t

Time:02-03

I have a repository service that uses an API to perform CRUD operations and when I create a record I need to run an update (to save a custom reference number that uses the ID (int SQL identity field)) generated by the Create method.

So if I have this in my controller method...

var response = await repository.Create(obj);

response.Result.Reference = _service.CreateReference(response.Result);

await repository.Update(response.Result);

Will the create always run to completion before the update gets called? (Because I'm using .Result)?

Thanks

CodePudding user response:

Short answer: Yes.

Everything in that method that comes after this line...

var response = await repository.Create(obj);

... is in a continuation - think of it as being put on hold until that line has completed. That does not mean that stuff outside your method is blocked; await means that other stuff can happen in parallel while waiting - that is the whole point after all.

What it does mean for your case is that the following two lines (and any others following them in the same method) are "put on a shelf" until the above is completed. Once it is completed, execution of these two will continue:

response.Result.Reference = _service.CreateReference(response.Result);
await repository.Update(response.Result);

At this point, the same rule goes for the last line:

await repository.Update(response.Result);

Any code in your method after this line will be in a second continuation, and will only be called once the operation from that line has completed.

  •  Tags:  
  • Related