I'd like to make a HTTP request when an object is being collected by the Garbage Collector. I put a simple call in the finailzer of the class, which works fine as long as the application is not shutting down.
When the program is finished and my application wants to shut down, the GC calls the finalizer as before, but this time the request get stuck or just exits without an exception. At least the Studio doesn't show an exception, the program just terminates when the call is sent.
Unfortunately I must use the finalizer to send this request, so please do not suggest to use Dispose instead of the finalizer. Let's just find a way to do it from there if possible. :)
Here is the important part of my code:
class MyExample
{
private readonly HttpClient myClient;
public MyExample()
{
var handler = new HttpClientHandler();
handler.UseProxy = false;
handler.ServerCertificateCustomValidationCallback = (a, b, c, d) => true;
this.myClient = new HttpClient(handler);
this.myClient.BaseAddress = new Uri("https://wonderfulServerHere");
}
public async void SendImportantData() => await this.myClient.SendAsync(new HttpRequestMessage(HttpMethod.Get, "ImportantData"));
~MyExample()
{
this.SendImportantData();
}
}
class Program
{
static void Main(string[] args)
{
MyExample ex = new MyExample();
/* ... */
ex = new MyExample();
/* ... */
GC.Collect();
GC.WaitForPendingFinalizers(); // Works fine here
/* ... */
} // Doesn't work here
}