我想在垃圾收集器收集對象時發出HTTP請求。我在這個班的最後一班給了一個簡單的電話,只要應用程序沒有關閉,工作正常。在.NET終結器中的HttpClient請求
當程序結束後,我的應用程序要關閉,GC作爲前調用終結,但這次請求被卡住或只是退出沒有例外。至少Studio不顯示異常,程序只在發送呼叫時終止。我不得不使用Dispose而不是終結器。如果可能的話,我們可以從中找到一種方法。 :)
這裏是我的代碼的重要組成部分:
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
}
你怎麼知道它不工作?沒有例外的退出代碼並不能證明它不起作用。你有意做一個POST幷包含一些數據而不是GET嗎?有沒有可能終結者只是沒有被調用的對象? – Luke
好問題。請求根本不在另一邊顯示。真正的代碼使用POST,這與GET示例沒有任何區別。 –
當運行時正在終止時,您無法做到這一點。但我很好奇什麼情況可能導致需要在終結器中發出Web請求? – Evk