I have an end point where a user can start an update operation. I don't want to make the user wait for the result. There are two possible outcomes:
- The action is succesful - nothing to do for the user.
- There is an exception - this is logged (every exception is) in WatchDog and the database admin checks this.
[HttpPatch("{joborderID}/[Action]")]
[SwaggerResponse(202)]
public IActionResult UpdateBlozoColumns(int joborderID)
{
joborderService.UpdateBlozoColumnsIfNecessary(joborderID);
return Accepted();
}
The UpdateBlozoColumnsIfNecessary:
internal async Task UpdateBlozoColumnsIfNecessary(int joborderID)
{
// Do something
}
Visual Studio warns:
Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.
Now if I am correct, when there is an exception, it isn't catched because it is in a task? How can I write this that the accepted-pattern is correct?
Would a "fire and forget" pattern be appropiate?
Task.Run(async () =>
{
try
{
await joborderService.UpdateBlozoColumnsIfNecessary(joborderID);
}
catch (Exception ex)
{
throw;
}
});
return Accepted();
Or
var task = joborderService.UpdateBlozoColumnsIfNecessary(joborderID);
task.ContinueWith(task =>
{
if (task.Exception is not null)
{
throw task.Exception;
}
});