In LINQ-SQL, wrap the DataContext is an using statement - pros cons

前端 未结 5 1482
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-02 10:41

Can someone pitch in their opinion about pros/cons between wrapping the DataContext in an using statement or not in LINQ-SQL in terms of factors as performance, memory usage, ea

5条回答
  •  攒了一身酷
    2021-02-02 11:26

    A DataContext can be expensive to create, relative to other things. However if you're done with it and want connections closed ASAP, this will do that, releasing any cached results from the context as well. Remember you're creating it no matter what, in this case you're just letting the garbage collector know there's more free stuff to get rid of.

    DataContext is made to be a short use object, use it, get the unit of work done, get out...that's precisely what you're doing with a using.

    So the advantages:

    • Quicker closed connections
    • Free memory from the dispose (Cached objects in the content)

    Downside - more code? But that shouldn't be a deterrent, you're using using properly here.

    Look here at the Microsoft answer: http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/2625b105-2cff-45ad-ba29-abdd763f74fe

    Short version of if you need to use using/.Dispose():

    The short answer; no, you don't have to, but you should...

提交回复
热议问题