Do you need to wait for asynchronous methods?

Suppose you have a service API call. The call is critical, therefore, in order not to delay the API call longer than necessary, there is a SaveAsync() method that is used. However, I cannot await , because it will delay the API call for as long (or perhaps even more) than the non-asynchronous version.

The reason I ask is this: if you are not await call, is there a chance to return a Task object to get garbage? And if so, will this interrupt the current task?

+6
source share
2 answers

The reason I ask is this: if you are not waiting for the call, is it likely that the Task object returned the garbage collected?

As a rule, no, this should not be. The main TaskScheduler , which queues the task, usually saves a link to it for the desired lifetime until it is completed. You can see this in the TaskScheduler.QueueTask documentation:

A typical implementation will store the task in an internal data structure that will be served by threads that will perform these tasks in the future.

Your real problem will be with the ASP.NET SynchronizationContext, which keeps track of any current asynchronous operation at runtime. If your controller expires before the async operation, you will get an exception.

If you want to have "fire and forget" in ASP.NET, you must definitely register them at runtime with ASP.NET, either through HostingEnvironment.QueueBackgroundWorkItem or BackgroundTaskManager

+6
source

No, he will not interrupt the task in progress, but you will not observe exceptions to the task, which is not entirely good. You can (at least partially) avoid this by wrapping all the running code in try ... catch and write the exception.

In addition, if you are inside asp.net, your application may be stopped or processed, in which case your task will be interrupted. This is harder to avoid - you can sign up for an AppPool disconnect notification or use something like Hangfire .

+2
source

All Articles