2

If I call an async function on a nameless instance, will the instance stay alive until the function finishes? For example, if I have a server that I need to run in the background for some time. I am not interested in the state of this server or in tracking it in any way. I may do something like this:

...
new MyServer().Start();
...
class MyServer {
  ...
  async Task Start() { ... }
  ...
}

will the Start method run till completion, or will the nameless referenceless instance be GC before it is finished running?

Baruch
  • 20,590
  • 28
  • 126
  • 201
  • I use a [GCHandle](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.gchandle) (as shown [here](https://stackoverflow.com/a/48812831/7444103), for example, to prevent the delegate from being *collected*) or a `SafeHandle` derived class object, in similar occasions. – Jimi Feb 02 '20 at 22:39

1 Answers1

1

There still is a reference behind the scenes. The continuation of the async method is registered with the SynchronizationContext that is set under SynchronizationContext.Current (or the Thread Pool if .Current is null) via its Post method. That continuation will keep the reference alive.

One thing to note, the above is only talking about the garbage collector collecting your class. If you are running in IIS your application domain may shut down before your task completes and that will terminate the server. If that is your case you should be using a IHostedService to keep your service up and running.

Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431
  • Does it make a difference if in the `async` function I use `.ConfigureAwait(false)`? – Baruch Feb 02 '20 at 23:08
  • ConfigureAwait(false) just makes it always use the default thread pool context instead of whatever is set in .Current – Scott Chamberlain Feb 02 '20 at 23:25
  • Another way to think about it, every `await` is syntactic sugar equivalent to `.GetAwaiter().OnCompleted(MoveNext)`. That reference to your state machines `MoveNext` will keep your task alive until the runtime / OS can resume your task. – Jeremy Lakeman Feb 03 '20 at 01:52