Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Context Switching in IsReusable Property

IsReusable Property

Below is my understanding for IsReusable Property

If the handler returns static content. it is safe to set the value to true. But if the thread returns dynamic content, to make it thread safe, IsReusable should be set to set as false.

In such case the Context Switching may occur, which may cause the handler to give wrong output.

Confusions

Context Switching says - Switching of one thread to another thread is called switching. right?

Paragraph 2 says context switching may occur - I think, when you send the request. That time only one context creates, which results in a Response. right? So, How Context Switching is possible. Can you give an example?

like image 851
SMC Avatar asked Jul 01 '13 14:07

SMC


1 Answers

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.

like image 129
usr Avatar answered Sep 17 '22 18:09

usr