7

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?

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
Alex
  • 3,429
  • 4
  • 36
  • 66
  • Can you show a bit of code where you would await this method? – Matteo Umili Sep 25 '15 at 15:04
  • 1
    Are you sure that await would be hold the API? As I know, await point would be stored at spacial block and when result would be came CLR would handled your await part of code – Oleh Dokuka Sep 25 '15 at 15:05

2 Answers2

7

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

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
  • Luckily for me, this is hosted in a windows service and not in asp.net. But that is good information for anyone who thinks of doing this in asp.net. – Alex Sep 25 '15 at 22:35
2

No, it won't interrupt the running task, but you won't observe the exceptions from the task either, which is not exactly good. You can (at least partially) avoid that by wrapping all running code in a try ... catch and log the exception.

Also, if you're inside asp.net, then your whole application could be stopped or recycled, and in this case your task will be interrupted. This is harder to avoid - you can register for AppPool shutdown notification, or use something like Hangfire.

Sergei Rogovtcev
  • 5,804
  • 2
  • 22
  • 35