Should I keep an instance of DbContext in a separate thread that performs periodic job

I have a class Worker which sends emails periodically,I start in Global.asax.cs on App_start()

public static class Worker { public static void Start() { ThreadPool.QueueUserWorkItem(o => Work()); } public static void Work() { var r = new DbContext(); var m = new MailSender(new SmtpServerConfig()); while (true) { Thread.Sleep(600000); try { var d = DateTime.Now.AddMinutes(-10); var ns = r.Set<Notification>().Where(o => o.SendEmail && !o.IsRead && o.Date < d); foreach (var n in ns) { m.SendEmailAsync("[email protected]", n.Email, NotifyMailTitle(n) + " - forums", NotifyMailBody(n)); n.SendEmail = false; } r.SaveChanges(); } catch (Exception ex) { ex.Raize(); } } } }

So I keep this dbcontext alive for the entire lifetime of the application is this a good practice ?

-------------Problems Reply------------

I would wrap it in a using statement inside of Work and let the database connection pool do it's thing:

using (DbContext r = new DbContext())

NOTE: I am not 100% sure how DbContext handles the db connections, I am assuming it opens one.

It is not good practice to keep a database connection 'alive' for the lifetime of an application. You should use a connection when needed and close it via the API(using statement will take care of that for you). The database connection pool will actually open and close connections based on connection demands.

DbContext is a very light-weight object.

It doesn't matter whether your DbContext stays alive or you instantiate it just before making the call because the actual DB Connection only opens when you SubmitChanges or Enumerate the query (in that case it is closed on end of enumeration).

In your specific case. It doesn't matter at all.

Read Linq DataContext and Dispose for details on this.

I agree with @rick schott that you should instantiate the DbContext when you need to use it rather than keep it around for the lifetime of the application. For more information, see Working with Objects (Entity Framework 4.1), especially the section on Lifetime:

When working with long-running context consider the following:

  • As you load more objects and their references into memory, the memory consumption of the context may increase rapidly. This may cause performance issues.
  • If an exception causes the context to be in an unrecoverable state, the whole application may terminate.
Category:c# Views:1 Time:2011-10-01

Related post

Copyright (C), All Rights Reserved.

processed in 0.158 (s). 11 q(s)