我的问题的来源是以下代码,它是Microsoft documentation中包含的代码片段的一部分,用于asp.net web api中的异常处理:
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
。
这是一个问题吗?不处理这些物体是否有任何副作用?
根据this article,可能的解决方案可能是将上述代码更改为以下内容:
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);
这是否真的有必要,还是可以避免这种情况(根据Microsoft文档中显示的内容)?
答案 0 :(得分:3)
检查Microsoft Source for HttpResponseMessage.CS:
protected virtual void Dispose(bool disposing)
{
// The reason for this type to implement IDisposable is that it contains instances of
// types that implement IDisposable (content).
if (disposing && !_disposed)
{
_disposed = true;
if (_content != null)
{
_content.Dispose();
}
}
}
content
的类型为HttpContent。检查Microsoft Source for HttpContent.cs:
protected override void Dispose(bool disposing)
{
Debug.Assert(_buffer != null);
ArrayPool<byte>.Shared.Return(_buffer);
_buffer = null;
base.Dispose(disposing);
}
ArrayPool的评论说:
/// Renting and returning buffers with an <see cref="ArrayPool{T}"/> can increase performance
/// in situations where arrays are created and destroyed frequently, resulting in significant
/// memory pressure on the garbage collector.
检查ArrayPool的源代码会产生这个可爱的宝石:
/// <summary>
/// Retrieves a shared <see cref="ArrayPool{T}"/> instance.
/// </summary>
/// <remarks>
/// The shared pool provides a default implementation of <see cref="ArrayPool{T}"/>
/// that's intended for general applicability. It maintains arrays of multiple sizes, and
/// may hand back a larger array than was actually requested, but will never hand back a smaller
/// array than was requested. Renting a buffer from it with <see cref="Rent"/> will result in an
/// existing buffer being taken from the pool if an appropriate buffer is available or in a new
/// buffer being allocated if one is not available.
/// </remarks>
public static ArrayPool<T> Shared
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return Volatile.Read(ref s_sharedInstance) ?? EnsureSharedCreated(); }
}
ArrayPool
不使用WeakReference
或任何类似的机制来确保妥善处置。如果从ArrayPool.Shared
租用缓冲区,则必须将其返回,否则会导致内存泄漏。
所以是的,我会说尊重IDisposable
在这里非常重要。
答案 1 :(得分:1)
由HttpResponseException
包装的响应将由asp.net框架处理,就像您从操作中返回的任何其他响应一样。您可以通过创建虚拟响应消息轻松测试自己:
class DummyResponse : HttpResponseMessage {
public DummyResponse(HttpStatusCode statusCode) : base(statusCode) {
}
protected override void Dispose(bool disposing) {
Console.WriteLine("dispose called");
base.Dispose(disposing);
}
}
然后使用该响应抛出HttpResponseException
并将断点放在Dispose
覆盖中。您将观察到Dispose
被调用,如果您查看调用堆栈,您将看到HttpControllerHandler
负责这样做(在asp.net web api控制器中)。
请注意,ApiControllerActionInvoker
这个负责调用api控制器操作的类会捕获此异常。然后它只抓取yourException.Response
并将其推送到管道中,因此抛出此异常与仅从api控制器操作返回相应的响应没有什么不同。应该很清楚,我认为框架将在完成后对所有这些响应进行处理。否则这将是非常糟糕的设计。
所以,不要让那些RegisterForDispose
的代码混乱,让框架为你处理。