Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 commit changes at the very end or should I create a Context per thread and use that instance for everything inside that thread?

like image 656
dkarzon Avatar asked Feb 07 '11 06:02

dkarzon


1 Answers

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...

like image 130
Marc Gravell Avatar answered Sep 23 '22 04:09

Marc Gravell