简体   繁体   English

LINQ to SQL和开放连接

[英]LINQ to SQL and open connections

I've always had in my data access layer the following kind of code setup (made up example) 我一直在数据访问层中进行以下类型的代码设置(组成示例)

public static class LoadData
{
  private static SomeDataContext db = new SomeDataContext();

  public static void LoadData(DropDownList ddl)
  {
    (from ls in db.MyLookup
    select ls).OrderBy(ls=>ls.theId).ToList()
    .ForEach(ls=>ddl.Items.Add(new ListItem(ls.theText, ls.theValue.ToString())));
  }
}

Is the DataContext "smart" enough to cleanup after itself or should I be wrapping my query with a using statement to make sure connections are closed? DataContext是否“聪明”到足以清理自身,还是应该using语句包装查询以确保关闭连接?

You should most definitely be, at least, using a using block when accessing the database. 您绝对应该至少在访问数据库时使用using块。 The Data Context does not automatically open and close the connections for you. 数据上下文不会自动为您打开和关闭连接。 You're still responsible for your resources. 您仍然要对自己的资源负责。

You might want to look into using the Unit of Work pattern in case you need to access the database multiple times using a single connection (related data, etc.). 如果您需要使用单个连接(相关数据等)多次访问数据库,则可能需要使用工作单元模式。

Is the DataContext "smart" enough to cleanup after itself DataContext是否“聪明”到足以自行清理

Data Context's are designed to be used in a small scope; 数据上下文被设计为在较小范围内使用。 that of a single transaction. 单笔交易。 As such they won't release any of their resources until you dispose of them and allow the object to go out of scope. 因此,除非您处置它们并允许对象超出范围,否则它们不会释放任何资源。 Using a single context through your entire application like this will result in the consumption of a significant amount of resources (including a network connection as well as memory (both managed and unmanaged)). 像这样在整个应用程序中使用单个上下文将导致大量资源的消耗(包括网络连接以及内存(托管和非托管))。

You should instead create a new data context for each LoadData call, and wrap the context in a using to ensure that it's properly disposed after each call. 您应该为每个LoadData调用创建一个新的数据上下文,并将该上下文包装在using以确保在每次调用之后将其正确处理。

As noted in comments the data context is also not thread safe, so that is yet another reason not to be re-using the same context across multiple logical transactions. 如注释中所述,数据上下文也不是线程安全的,因此另一个原因是不要在多个逻辑事务中重用同一上下文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM