在操作方法

时间:2018-05-22 18:02:47

标签: c# asp.net asp.net-web-api idisposable

我的问题的来源是以下代码,它是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);

HttpResponseMessageStringContent都实现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文档中显示的内容)?

2 个答案:

答案 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的代码混乱,让框架为你处理。