Reputation: 31
I am writing a simple console application that does only the following:
1. Query the database for some data.
2. Process this data.
3. Update the database.
I wrote the code, which consists only of the Main method, like the following:
class Program
{
static void Main(string[] args)
{
try
{
var dbContext = new MyDatabaseContext();
var dbRecord = dbContext.MyTable.First(r => r.Status == 1);
// Do some work
dbRecord.Status = 2;
dbContext.SaveChanges();
}
catch(Exception)
{
// left empty
}
}
}
A colleague of mine told me that I must enclose the code within a "using" statement to close the connection between the application and the database server, like the following:
class Program
{
static void Main(string[] args)
{
try
{
using(var dbContext = new MyDatabaseContext())
{
var dbRecord = dbContext.MyTable.First(r => r.Status == 1);
// Do some work
dbRecord.Status = 2;
dbContext.SaveChanges();
}
}
catch(Exception)
{
// left empty
}
}
}
I know the importance of disposing an "IDisposable" object, before leaving a scope or when the object is no longer needed, to avoid memory leak and to release resources.
But my understanding is, in my case, the program already ends and I don't need to explicitly dispose the DbContext as no connection will exist between the application and the database server after the application ends.
So, I need to answer the following:
1.Is it important, in my case, to dispose the DbContext object before the program exits?
2. Will the connection be still open even after closing the program (Normally, with an exception, or closed by the user)?
3. What will happen if I don't use the "using" statement?
I will be thankful if you provide the answers with official references.
Please note that my concern is memory and resource leaks. Data loss is not my concern for now.
Upvotes: 3
Views: 713
Reputation: 1134
To answer to your 3 questions:
Upvotes: 1