在我的字典被填充后,我的SQL连接会保持打开状态吗?

3
在下面的代码示例中,当"ListOfLists"方法完成后,我的数据上下文连接是否会保持打开状态?我需要显式关闭它吗,还是它会保持打开状态并可供其他方法使用。
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;
            }
        }

像这样捕获异常对象是不好的实践。首先,您正在吞咽异常,这将使以后调试更加困难。其次,您没有任何异常可以处理,例如catch(Exception e)。第三,除非您实际上要处理异常的原因并修复它,或者尝试再次执行它,否则应该throw异常,以便在调用堆栈中进一步处理它。 - Stuart Grassie
1个回答

2

它仍然是打开的。您需要显式处理/关闭连接,否则可能会出现内存或连接池问题。我建议您将上下文包装在 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;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接