我可以在using()之外声明一个上下文并仍然可以调用Dispose()吗?

时间:2012-07-17 09:09:58

标签: c# garbage-collection datacontext using

我有一个类FooDataContext,它实现了Linq的DataContext,它有Dispose() ..

public partial class FooDataContext : System.Data.Linq.DataContext {...}

我知道我应该在using(<here>){}内声明fooDataContext,因此我会调用Dispose(),就像这样

public void Bar()
{
    using (var fooDataContext = new FooDataContext(ConnStr))
    { // some code
    }
}

但我不知道这是否同样好。是吗?幕后发生了什么?

public void Baz()
{
    var fooDataContext = new FooDataContext(ConnStr);
    using (fooDataContext)
    { // some code
    }
}

2 个答案:

答案 0 :(得分:4)

后者基本上会以相同的方式运行,但有一个缺点:你仍然可以在fooDataContext 外面引用using语句,尽管事实上它已被处理掉了。这不是一个好主意。

所以是的,使用第二个片段是完全合法的 - 但几乎在所有情况下你都应该更喜欢第一个版本。

答案 1 :(得分:2)

实例与using之间可能会发生异常,尤其是在添加自定义代码时。在使用中调用构造函数更安全。此外,使用第一种解决方案可以防止使用已处理的上下文。

public void Baz() 
{ 
    var fooDataContext = new FooDataContext(ConnStr); 
    //Exception here -> fooDataContext not disposed
    using (fooDataContext) 
    { // some code 
    }
    //You can see fooDataContext here
} 

如果您真的想在fooDataContext之后看到using变量,可以试试这个:

public void Baz() 
{ 
    var fooDataContext; 
    using (fooDataContext = new FooDataContext(ConnStr))
    { // some code 
    } 
    //You can see fooDataContext here
}