Alex Alex - 2 months ago 8
C# Question

Do you have to await async methods?

Lets say you have a service API call. The callee is somewhat performance critical, so in order not to hold up the API call any longer than necessary, there's an

SaveAsync()
method that is used. I can't
await
it, however, because that would hold up the API call just as long (or perhaps even longer) than the non-async version.

The reason I'm asking is this: If you don't
await
the call, is there a chance the
Task
object returned gets garbage collected? And if so, would that interrupt the running task?

Answer

The reason I'm asking is this: If you don't await the call, is there a chance the Task object returned gets garbage collected?

Generally, no, that shouldn't happen. The underlying TaskScheduler which queues the task, usually keeps a reference to it for the desired life-time until it completes. You can see that in the documentation of TaskScheduler.QueueTask:

A typical implementation would store the task in an internal data structure, which would be serviced by threads that would execute those tasks at some time in the future.

Your real problem is going to be with the ASP.NET SynchronizationContext, which keeps track of any on-going asynchronous operation at runtime. If your controller action finishes prior to the async operation, you're going to get an exception.

If you want to have "fire and forget" operations in ASP.NET, you should make sure to register them with the ASP.NET runtime, either via HostingEnvironment.QueueBackgroundWorkItem or BackgroundTaskManager