Reputation: 61755
Given this code:
/// <summary>
/// Add to view count of this article
/// </summary>
public static void IncrementViewCount(int articleID)
{
using (var db = new MainContext())
{
var q = (from c in db.tblArticles where c.ID == articleID select c).SingleOrDefault();
if (q != null)
{
q.Views ++;
db.SubmitChanges();
if (q.Views == 500)
{
// Call function
}
}
}
}
Is it better to write it in the follow way:
/// <summary>
/// Add to view count of this article
/// </summary>
public static void IncrementViewCount(int articleID)
{
var newViews = 0;
using (var db = new MainContext())
{
var q = (from c in db.tblArticles where c.ID == articleID select c).SingleOrDefault();
if (q != null)
{
newViews = q.Views + 1;
q.Views = newViews;
db.SubmitChanges();
}
}
if (newViews == 500)
{
// Call function
}
}
Note in example #2, the using block is closed at an earlier point.
Upvotes: 0
Views: 163
Reputation: 60506
Depending on how long your "function" takes and you don't need the context, the second is better.
Read this
There are a few reasons we implemented IDisposable:
If application logic needs to hold onto an entity beyond when the DataContext is expected to be used or valid you can enforce that contract by calling Dispose. Deferred loaders in that entity will still be referencing the DataContext and will try to use it if any code attempts to navigate the deferred properties. These attempts will fail. Dispose also forces the DataContext to dump its cache of materialized entities so that a single cached entity will not accidentally keep alive all entities materialized through that DataContext, which would otherwise cause what appears to be a memory leak.
The logic that automatically closes the DataContext connection can be tricked into leaving the connection open. The DataContext relies on the application code enumerating all results of a query since getting to the end of a resultset triggers the connection to close. If the application uses IEnumerable's MoveNext method instead of a foreach statement in C# or VB, you can exit the enumeration prematurely. If your application experiences problems with connections not closing and you suspect the automatic closing behavior is not working you can use the Dispose pattern as a work around.u don't need them.
Upvotes: 1