开发者

Is there an advantage to USING vs. declaring a context variable?

开发者 https://www.devze.com 2022-12-10 03:36 出处:网络
These two snippets do the same thing - is there one that\'s better than the other, or is it just a matter of preference?

These two snippets do the same thing - is there one that's better than the other, or is it just a matter of preference?

Using context As MyDatabaseDataContext = New MyDatabaseDataContext()
    Dim test = context.Employees.Count
End Using

vs.

Dim context As MyDatabaseDataContext = New MyDatabaseDataContext()
Dim test = context.Employees.Count

I realize thes开发者_如何学运维e are oversimplified examples - what are the scenarios where one one method would work better than the other?


The first calls Dispose at the end of the Using statement - that's the point of the Using statement. It's equivalent to Try/Finally, so the resource is disposed even if an exception is thrown.


Tony the Pony's answer is exact, the point of Using is to dispose unmanaged resources once you're done with the object. The equivalent code to:

Using context As New MyDatabaseDataContext()
    Dim test = context.Employees.Count
End Using

would be:

Dim context As New MyDatabaseDataContext()
Try
    Dim test = context.Employees.Count
Finally
    If context IsNot Nothing
        context.Dispose()
    End If
End If


The two snippets do NOT do the same thing. The first will dispose your data context at the end of the using block, even if an exception is thrown. The latter snippet will not dispose it, which potentially leaves an extra database connection hanging around.


The first one calls dispose at the end of the Using block. So yes there is an advantage there.

With LINQ2SQL DataContext's you have to be careful with deferred execution. You wouldn't want to put a deferred query in the Using block and after the Using block enumerate the results. You'll get an exception about the context being disposed.

You also have to be careful when using the Using block with WCF Service Clients. You can encounter problems with exception propagation.


when you use using - the object is destroyed in the end of the scope of using, and not later. if the object has special resources to dispose - it will release them earlier - so when you use a db connection -it will be smart using "using" for example.


Using guaranties that Dispose method will be called on context at the end of the block, even if exception was thrown.

It is important when working with disposable resources like files, db connections, etc.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号