1
There is a safe way not to wait for a process on . NET?
async Task DoFoo()
{
// ...
GravarLog();
// ...
}
void GravarLog()
{
// ...
}
In the above code, my entire process will wait for the method to be completed GravarLog()
, which to me is not necessary, and that method could be executed in background, without me having to wait for it to run the rest of my code. (log recording was just an example I used to contextualize)
An alternative, however highly volatile, would be async void
as a "fire and Forget" (or "fire and crash"):
async Task DoFoo()
{
// ...
GravarLog();
// ...
}
async void GravarLog()
{
// ...
}
There are many articles and opinions saying to avoid at all costs using async void
, because the exception control is different from the . NET standard:
- haacked.com: Avoid async void methods
- MSDN: Async/Await - Best Practices in Asynchronous Programming
- Sopt: When not returning Task in asynchronous method?
How not to "wait" for a method to be completed safely?
I see no problem in waiting to record a log, because (until today what I saw) recording logs is something very fast. But if it is a cumbersome process, have you considered delegating this responsibility to a Task Scheduler?
– Gabriel Katakura
I’ve never done the treatment of these cases manually (I didn’t have to), I’ve always used tools for this, so I can’t explain how to do the manual process of controlling this. But one tool that takes very good care of it is Hangfire.
– Gabriel Katakura
@Gabrielkatakura was the way I found to contextualize: logs, telemetry =P. I’ll take a look at this Hangfire.
– vinibrsl