我想在垃圾收集器收集对象时发出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