Context Switching in IsReusable Property

前端 未结 1 756
日久生厌
日久生厌 2021-02-14 21:17

IsReusable Property

Below is my understanding for IsReusable Property

If the handler returns static content. it

1条回答
  •  温柔的废话
    2021-02-14 22:12

    The question what the handler "returns" (better phrased: what content the handler writes) has nothing to do with the IsReusable property. This property makes a statement about the thread-safety of your code, not about whether the content can change. For example, a handler that writes DateTime.Now would be reusable. A handler that has an SqlConnection field and reads unchanging data would not be reusable because the connection is not thread-safe even if the data read is always the same.

    Context switching also has nothing to do with this because on a multi-core box no context switch is necessary to cause concurrency. What you mean is "thread-safety" with respect to concurrent invocations of ProcessRequest on the same instance of your IHttpHandler derived class.

    Now some practical advice: always have IsReusable return false and ensure that your handler class is cheap to allocate and does not bring tons of garbage with it. GC'ing a single object is nothing! My guess is the IsReusable property was created to give ASP.NET an artificial advantage in toy benchmarks, or to support poorly architected handlers that are expensive to create.

    If you have expensive resources (like caches) store them elsewhere (in a static field maybe).

    An easy way to obtain thread-safety is to not share anything. In that sense, don't share the handler.

    TL;DR: Set IsReusable to false and move on. Nothing to see here. This is just a confusing design flaw in ASP.NET.

    0 讨论(0)
提交回复
热议问题