0

Is it recommended to await "_teamRepository.AddTeamToDbAsync(teamToAdd)" method? Its just for saving to db no further validations etc. If I dont await save operation I provide faster result but are there some risks I am not aware of?

public async Task<OperationResult<TeamDto>> AddTeamAsync(TeamForCreationDto team)
        {
            var teamToAdd = _mapper.Map<Team>(team);
            bool IsNameTaken = await CheckIfTeamExistsAsync(team.Name);

            if (IsNameTaken)
            {
                return new OperationResult<TeamDto>
                {
                    IsSuccess = false,
                    ErrorMessage = "Provided name is already taken.",
                    HttpResponseCode = 409
                };
            }
            else
            {
                _teamRepository.AddTeamToDbAsync(teamToAdd);          // HERE
                var teamToReturn = _mapper.Map<TeamDto>(teamToAdd);
                return new OperationResult<TeamDto>
                {
                    IsSuccess = true,
                    Data = teamToReturn,
                    HttpResponseCode = 201
                };
            }
        }

Let me know what you think and if I understand it correctly

  • 1
    If you don't await the call, it could fail and you would report IsSuccess = true to the caller even though that was not the case. – juunas Jul 26 '23 at 01:34
  • 1
    Related: [Web Api - Fire and Forget](https://stackoverflow.com/questions/36335345/web-api-fire-and-forget). – Theodor Zoulias Jul 26 '23 at 01:40

1 Answers1

5

You should await it.

If you do not, then your code will return success before the operation is successful. Some validations like unique and foreign key constraints are checked during the save and cannot be known to be successful until after the save completes.

Furthermore, the normal pattern is to dispose the db context when the controller action completes; this may cancel the save (after a successful response is returned).

Finally, any time you have code that outlives a request, it may be terminated without warning any time the host shuts down (e.g., during a rolling upgrade).

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810