【问题标题】:return inside using statement在 using 语句中返回
【发布时间】:2013-12-01 18:26:01
【问题描述】:

我有以下函数,它接受员工 id 并在员工处于活动状态时返回。

public employee GetEmployee(int empId)
{ 
  using(var dbcontext = new dbentities())
  {
    return dbcontext.employee.Where(emp => emp.id == empId and emp.IsActive == true);
  }
}

问题:我使用了using 语句,因此只要 using 块结束,在 using 语句中创建的对象就会被释放。但是,在这里,我已经在实际 using 块结束之前编写了 return 语句,那么我的对象是否会被释放?我的方法正确吗?处置是如何发生的?

【问题讨论】:

    标签: c# entity-framework


    【解决方案1】:

    唯一被处理的是using 块中明确声明的东西——即分配给dbcontext 的东西。实际的员工对象处置,并且完全可用 - 但是,由于数据上下文不可用,任何特性(如延迟加载或对象导航)都将拒绝工作。

    顺便说一句 - 应该是 SingleSingleOrDefault:

    return dbcontext.employee.Single(
       emp => emp.id == empId and emp.IsActive == true);
    

    从技术上讲,在 IL 级别上,您不能在 try 块中使用 ret(这适用于所有代码,而不仅仅是 using),因此它实际上就像是编写的一样实现:

    public employee GetEmployee(int empId)
    {
        employee <>tmp;
        dbentities dbcontext = new dbentities();
        try {
          <>tmp = dbcontext.employee.Single(
             emp => emp.id == empId and emp.IsActive == true);
        } finally {
          if(dbcontext != null) ((IDisposable)dbcontext).Dispose();
          // note that for classes this cast is a no-op and doesn't need any IL;
          // the above gets a little more complex for structs - using
          // constrained call and no null-check
        }
        return <>tmp;
    }
    

    【讨论】:

    • 而且and 不是 C# 关键字。
    【解决方案2】:

    using 语句实际上的行为类似于 Try/Finally,如下所示:

        try
        {
            var dbcontext = new dbentities()
            return dbcontext.employee.where(emp => emp.id == empId and emp.IsActive == true);
        }
        finally
        {
             if(dbcontext != null)
                 ((IDisposable)dbcontext).Dispose(); //Per the comment below
        }
    

    finally总是无论如何都会被执行,所以上下文总是会被释放。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-25
    • 1970-01-01
    • 1970-01-01
    • 2014-02-27
    • 2013-09-06
    • 2019-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多