locked
Shares DbContext for multiple threads RRS feed

  • Question

  • User-1786262203 posted

    Is sharing database context (System.Data.Entity.DbContext) and entities for multiple threads is safe?

    or should i create many db context for many threads?

    Is db connection connectionfull or connectionless? What happen if i forget to call .Dispose() ?

    Tuesday, December 6, 2011 9:49 PM

Answers

  • User-1757793930 posted

    Here is the MSDN Wording on DbContext thread safety

    "Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe."

    Although static members are safe, the instance based objects are not thread safe. As a rule of thumb (personally) I try not to share my DataContext's across threads, or even methods really.

    If you need to use a context in another thread create a new context there. If you need to transfer an object (retrieved from a DataContext) to a Thread then detach the object from Entity Context. Then in your thread create a new Entity Context and attach your entity to the newly created context.

    As for the db context itself, it has been designed to automatically dispose of itself after the objects have been destroyed. Although this is I tend to always call the "Dispose" method after i have finished with my DataContext and \ or the objects retrieved. Following this pattern ensures that all your connections are closed.

    As for ConnectionFull vs ConnectionLess I have personally never heard this term. However if I understand you correctly does the connection stay open during the lifetime of the DataContext.

    The DataContext only opens, reads (using DataReader) when the objects are retrieved or enumerated and then closed and disposed of once the collection (or object) has been retrieved. Now how this works if you have the following code

    var myObj = new MyDataContext().Objects
    
    //
    //do some stuff that does not refereny myObj
    //
    
    foreach(var obj in myObj)
    {
       //
       //do something with my object
       //
    }

    Your data connection is not opened until the foreach statement, and then closed as soon as the GetEnumerator() method is called on your object collection.

    Now although the connection is closed the DataContext remains "Attached" to your object(s) until the DataContext is disposed off allowing the DataContext to open a new connection to modify the object.

    I hope this helps answer your questopn

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, December 6, 2011 11:00 PM