我的问题来源于以下代码,它是包含在 Microsoft 文档中的代码片段的一部分,用于 asp.net web api 的异常处理:Microsoft documentation。
var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new StringContent(string.Format("No product with ID = {0}", id)),
ReasonPhrase = "Product ID Not Found"
};
throw new HttpResponseException(resp);
在上面的代码中,HttpResponseMessage
和StringContent
都实现了IDisposable
接口,但是没有一个调用IDisposable.Dispose
方法。
这是一个问题吗?不释放这些对象会有什么副作用吗?
根据这篇文章,可能的解决方法是将上面的代码更改为以下内容:
var content = new StringContent(string.Format("No product with ID = {0}", id));
var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = content,
ReasonPhrase = "Product ID Not Found"
};
this.Request.RegisterForDispose(content);
this.Request.RegisterForDispose(resp);
throw new HttpResponseException(resp);
这真的必要吗?或者根据微软文档中所展示的,有没有可能避免这种情况?