Imagine that I will make an async call in .NET, i.e. HttpWebRequest.BeginGetResponse, and the HttpWebRequest object isn’t referenced at a broader scope. Will the Garbage Collector destroy it and cause problems?
Example code:
using System; using System.Net; public class AsyncHttpWebRequest { void Main() { var Request = HttpWebRequest.Create('http://www.contoso.com'); var result = Request.BeginGetResponse(GetResponseCallback, null); } private void GetResponseCallback(IAsyncResult AsyncResult) { // Do Something.. } }
Alternate version (with the request being passed as an AsyncState):
using System; using System.Net; public class AsyncHttpWebRequest { void Main() { var Request = HttpWebRequest.Create('http://www.contoso.com'); var result = Request.BeginGetResponse(GetResponseCallback, Request); } private void GetResponseCallback(IAsyncResult AsyncResult) { // Do Something.. } }
An object is considered alive and non-eligible for garbage collection if any live thread contains a reference to it, or if it’s referenced statically (directly or indirectly in both cases).
In both examples the async API keeps a reference to your request (within the thread pool where async IO operations are lodged) and so it won’t be garbage collected until it completes.