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?

1
  • I use a GCHandle (as shown here, for example, to prevent the delegate from being collected) or a SafeHandle derived class object, in similar occasions. Commented Feb 2, 2020 at 22:39

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Does it make a difference if in the async function I use .ConfigureAwait(false)?
ConfigureAwait(false) just makes it always use the default thread pool context instead of whatever is set in .Current
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.