Will my SQL connection remain open after filling out my dictionary

In the code sample below, will my data context connection remain open after the ListOfLists method finishes? I need to explicitly close it, or it will remain open and be available to other methods.

public static Dictionary<int, string > ListOfLists()
        {
            try
            {
                ListDataDataContext db = new ListDataDataContext(GetConnectionString("Master"));

                return db.ListMatchingHeaders
                    .Select(r => new { r.ListRecNum, r.ListName })
                    .ToDictionary(t => t.ListRecNum, t => t.ListName);
            }
            catch (Exception)
            {
                MessageBox.Show("Could not connect to database, please check connection and try again", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
        }
+3
source share
1 answer

He is still open. You will need to explicitly establish / close the connection, or perhaps you may have problems with memory or the connection pool. I recommend that you wrap your context around a block using.

public static Dictionary<int, string> ListOfLists()
{
    try
    {
        using (ListDataDataContext db = new ListDataDataContext(GetConnectionString("Master")))
        {
            return db.ListMatchingHeaders
                .Select(r => new { r.ListRecNum, r.ListName })
                .ToDictionary(t => t.ListRecNum, t => t.ListName);
        }
    }
    catch (Exception)
    {
        MessageBox.Show("Could not connect to database, please check connection and try again", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        return null;
    }
}
+2
source

Source: https://habr.com/ru/post/1763903/


All Articles