Linq-to-SQL DataContext across multiple threads
How do I handle a Linq-to_SQL DataContext across multiple threads?
Should I be creating a global static DataContext that all the threads use and comm开发者_JAVA技巧it changes at the very end or should I create a Context per thread and use that instance for everything inside that thread?
DataContext
is not thread safe; using it directly from multiple threads would cause #fail; having a global static data-context would cause #fail and would cause uncontrolled memory growth (the data-context includes an identity manager and change tracker for every object fetched; this only grows over time, as more objects are touched)
Data context should ideally be used for a unit of work; spin one up; do something (that is bound in scope - i.e. not the entire app lifetime), and dispose it. So IMO the real answer here is "tie it to that unit of work". Only you can know what that is in your application; it could be a single method, it could a page request on a web page, it could be a timer "tick" in a service. Who knows...
精彩评论