[英]Catching OutOfMemory Exceptions from HttpClient.GetAsync()
我正在执行一个相当简单的 HttpClient.GetAsync() 调用,如果我的调用目标存在(它是在我的本地 PC 上运行的 Web 服务),那么我会正确获取数据,并且一切都如宣传的那样工作。 但是,如果我调用的目标不存在,我偶尔会抛出 OutOfMemory 异常。 然而,我实际上似乎无法捕捉到这个异常。 这是我拨打电话的方式:
注意: proxy
只是我的类的一个私有HttpClient
成员,它已经被初始化/创建。
public static T get(string methodNameParam)
{
T returnValue = default(T);
try
{
string getString = $"remoteAPI/get/{methodNameParam}";
HttpResponseMessage response = proxy.GetAsync(getString).Result;
if(response.IsSuccessStatusCode)
{
String jsonString = response.Content.ReadAsStringAsync().Result;
returnValue = JsonConvert.DeserializeObject<T>(jsonString);
}
}
catch (Exception ex)
{
// log exception thrown, allow upper functions to manage it.
logger.LogError($"Error Get {methodNameParam} ", ex);
throw;
}
return returnValue;
}
OutOfMemory 异常永远不会被捕获,我假设是因为它是在 Async 调用的上下文中抛出的? 我怎样才能捕捉到这个异常,如果只是记录它发生了(目前我的应用程序崩溃并烧毁)。
编辑:我根据 Selvin 的反馈更新了函数,现在看起来像:
private static async Task<HttpResponseMessage> _get(string getString)
{
HttpResponseMessage response = default(HttpResponseMessage);
try
{
response = await proxy.GetAsync(getString);
}
catch (Exception ex)
{
logger.LogError($"Error (_get) - Caught Exception! ", ex);
}
return response;
}
public static T get(string methodNameParam)
{
T returnValue = default(T);
try
{
string getString = $"remoteAPI/get/{methodNameParam}";
HttpResponseMessage response = _get(getString).Result;
if(response.IsSuccessStatusCode)
{
String jsonString = response.Content.ReadAsStringAsync().Result;
returnValue = JsonConvert.DeserializeObject<T>(jsonString);
}
}
catch (Exception ex)
{
// log exception thrown, allow upper functions to manage it.
logger.LogError($"Error Get {methodNameParam} ", ex);
throw;
}
return returnValue;
}
但是,只要调用.GetAsync()
函数,VS19 调试器仍然get()
在调用_get()
在同步get()
调用中捕获未处理的 Out of Memory 异常。
OutOfMemoryException
是一个异步异常——你不能保证它会发生在给定的线程上。 即使你抓住了它,你的进程也可能处于不一致的状态,所以你可能最好让它崩溃而不是延长它几乎肯定的死亡时间。
您最好的策略可能是处理AppDomain.UnhandledException
而不是出于日志记录目的。 请参阅https://docs.microsoft.com/en-us/dotnet/api/system.appdomain.unhandledexception?view=net-5.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.