Although DataContext/ObjectContext implement IDisposable, you can (in general)
get away without disposing instances. Disposing forces the context’s connection
to dispose—but this is usually unnecessary because L2S and EF close connections
automatically whenever you finish retrieving results from a query.
Disposing a context can actually be problematic because of lazy evaluation. Con-
sider the following:
IQueryable<Customer> GetCustomers (string prefix)
{
using (var dc = new NutshellContext ("connection string"))
return dc.GetTable<Customer>()
.Where (c => c.Name.StartsWith (prefix));
}
...
foreach (Customer c in GetCustomers ("a"))
Console.WriteLine (c.Name);
This will fail because the query is evaluated when we enumerate it—which is
after disposing its DataContext.
There are some caveats, though, on not disposing contexts:
• It relies on the connection object releasing all unmanaged resources on the
Close method. While this holds true with SqlConnection, it’s theoretically
possible for a third-party connection to keep resources open if you call
Close but not Dispose (though this would arguably violate the contract de-
fined by IDbConnection.Close).
• If you manually call GetEnumerator on a query (instead of using foreach) and
then fail to either dispose the enumerator or consume the sequence, the con-
nection will remain open. Disposing the DataContext/ObjectContext provides
a backup in such scenarios.
• Some people feel that it’s tidier to dispose contexts (and all objects that im-
plement IDisposable).
If you want to explicitly dispose contexts, you must pass a DataContext/Object
Context instance into methods such as GetCustomers to avoid the problem
described.
'.NET > C#' 카테고리의 다른 글
[영어, 영상] What is new in C# 6.0 (0) | 2013.08.20 |
---|---|
[C#] How to display an XML file to Console (0) | 2013.07.24 |
ADO.NET Entity Model 짧은 강좌 (0) | 2013.06.18 |
[스크랩] [영어 원문] C#: Currying (0) | 2013.06.12 |
Directory.GetFiles() with multiple filters (0) | 2013.06.09 |