Proper use of “Using” statement for datacontext

后端 未结 5 513
醉酒成梦
醉酒成梦 2021-02-06 05:08

I’m using Linq to Entities and lately, I found that a lot of folks recommending wrapping the datacontext in a using statement like this:

Using(DataContext db = n         


        
5条回答
  •  别那么骄傲
    2021-02-06 05:57

    The DataContext class is wrapped in a Using statement because it implements the IDisposable interface.

    Internal to the DataContext it is using SqlConnection objects and SqlCommand objects. In order to correctly release these connection back to the Sql Connection Pool, they need to be disposed of.

    The garbage collector will eventually do this, but it will take two passes due to the way IDisposable objects are managed.

    It's strongly encouraged that Dispose is called and the Using statement is a nice way to do this.

    Read these links for more indepth explanation:

    http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/2625b105-2cff-45ad-ba29-abdd763f74fe/

    http://www.c-sharpcorner.com/UploadFile/DipalChoksi/UnderstandingGarbageCollectioninNETFramework11292005051110AM/UnderstandingGarbageCollectioninNETFramework.aspx

提交回复
热议问题