"Even though you do not use Threads in an application explicitly, its bound to be thread unsafe if you are talking about web server applications"开发者_如何学运维.
I just want to understand this clearly. Assume i have a restful service (ASP.net ; will talk about asp.net web application in picture). If there are two simultaneous requests to the same web method A, both of these are going to be served by different thread of the IIS wp. Now, what are these 2 threads working on? ie. Are these two threads accessing A on the same instance of the service class?
How can we validate the fact that these 2 requests are/ are not working on the same instance of the service class so that there is infact a thread unsafety here because of instance variables being accessed in the web method
> Now, what are these 2 threads working on?
Short answer threads of IIS. You need clarify architecture of IIS - think about this as stand alone program. It can plug (dynamically load) lot of DLLs. One of it is ASP.Net interceptor (it accept extensions looked like *.aspx, *.ashx, ...) In other turn this DLL loads your DLLs produced from your code. So to handle request from client side IIS (in general case) starts thread (let me skip discussion of pooling).
> How can we validate the fact that these 2 requests are/ are not working on the same instance of the service class
In scenario above you don't need to validate, since ASP.Net will create as many instance as you need. The problem appears when you use asynchronous request feature (see http://msdn.microsoft.com/en-us/magazine/cc163725.aspx)
<%@ Page Async="true" ... %>
Or start some threads manually.
In both cases you could apply really powerful set of synchronization primitives to detect if some resource is shared between 2 or more threads. Using atomic increments (Interlocked.Increment/Decrement
) or Monitor with TryEnter methods (for details see http://msdn.microsoft.com/en-us/magazine/cc188793.aspx)
精彩评论