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

前端 未结 5 1485
爱一瞬间的悲伤
爱一瞬间的悲伤 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:23

    In one particular application, I experienced that, without wrapping the DataContext in using block, the amount of memory usage kept on increasing as the live objects were not released for GC. As in, in below example, if I hold the reference to List

    object and access entities of q, I create an object graph that is not released for GC.

    DBDataContext db = new DBDataContext()
    var qs = 
        from x in db.Tables
        where x.Id == someId
        select x;
    
    return qs.toList();
    
    foreach(q in qs)
    {
        process(q);
        // cannot dispose datacontext here as the 2nd iteration 
        // will throw datacontext already disposed exception 
        // while accessing the entity of q in process() function
        //db.Dispose();
    }
    
    process(Table q)
    {
        // access entity of q which uses deferred execution
        // if datacontext is already disposed, then datacontext 
        // already disposed exception is thrown
    }
    

    Given this example, I cannot dispose the datacontext because all the Table instances in list variable qs **share the same datacontext. After Dispose(), accessing the entity in process(Table q) throws a datacontext already disposed exception.

    The ugly kluge, for me, was to remove all the entity references for q objects after the foreach loop. The better way is to of course use the using statement.

    As far as my experience goes, I would say use the using statement.

    提交回复
    热议问题