14

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?

1 Answer 1

15

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

Sign up to request clarification or add additional context in comments.

3 Comments

@Rancur3p1c "why": because collections are rarely thread-safe, and having the same context talking on the same connection multiple times at once would be a nightmare. The usual disclaimer is there: "Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe." see msdn.microsoft.com/en-us/library/…
@Marc Gravell: Not thread-safe is not the same as failing when accessed from a different thread. Access to global variables from different threads can be done in a safe manner as long as proper locking mechanisms are in place. In contrast, access from non-UI threads to UI elements is truly forbidden and will cause runtime exceptions. Invoke from background threads into the UI thread is required in such cases. On what documentation do you base your #fail claim? Because you make it sound like the UI thread case...
@Christoph anything that could cause mutation to the model is going to be unmaneagably complex; since data-context has multiple levels of lazy load, mutation happens even when just reading it - basically, you'd need a global lock even to read the model. It talks to DbConnection, which touches thread-based state (ambient transactions, for example) And on top of that: you have things like events, which are going to get raised on arbitrary threads. Being shared between threads simply isn't a scenario that data-context targets, and it is going to end very badly.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.