堆叠使用语句与单独的using语句

问题描述 投票:2回答:3

在重构代码时,我偶然发现了一些堆叠的使用语句(我说的是10到15-ish)。

using(X x=new X())
using(Y y=new Y())
using(Z z=new Z())
using(...)
{
    List<X> listX= x.GetParameterListByID(pID);
    List<Y> listY=y.GetParameterListByID(pID);
    ...
    ...
    //other (business) calls/code, like 20-30 lines, that don't need the using instances
}

类示例就像是

public class X : IDisposable{
  public List<XParameterInfo> GetParameterListByID(int? pID){
      const string query="SELECT name,value FROM parameters WHERE id=@ID";
      //query code here
      return queryResult;
  }
}

我想到的第一件事是,知道using基本上是try{} finally{ x.Dispose(); },使用连接将保持打开/活动,直到使用块内的代码完成,而只需要填充一个列表。

以上是我的假设,如果我错了,请纠正我。考虑到我所说的是正确的,写出类似的东西会更好(表现,但大多数是好的练习)

List<X> listX;
List<Y> listY;
List<Z> listZ;
...
//for the example here I wrote out 3 but let's talk 10 or more

using(X x=new X())
{ 
   listX=x.GetParameterListByID(pID);
}
using(Y y=new Y())
{ 
   listY=y.GetParameterListByID(pID);
}
using(Z z=new Z())
{ 
   listZ=z.GetParameterListByID(pID);
} 
...
// other calls but now outside the using statements

或者它可以忽略不计,除了叠加的using语句带走嵌套代码外观的事实?

c# performance using-statement
3个回答
3
投票

它会更好(表现明智)

这取决于使用中使用的类型。你不能做一般性陈述。

性能不是唯一因素,开放资源可以阻止其他进程或导致内存问题。但另一方面,第一版更紧凑,可读性也有所提高。所以你必须决定是否存在问题。如果没有,为什么要这么麻烦?然后选择最佳可读和可维护的代码。

但您可以重构代码,使用方法封装使用:

// in class X:
public static List<X> GetParameterListByID(int pID)
{
    using(X x = new X())
    { 
       return x.GetParameterListByID(pID);
    }
} 
// and same in other classes

现在代码没有使用:

List<X> listX = X.GetParameterListByID(pID); // static method called
List<Y> listY = Y.GetParameterListByID(pID); // static method called

2
投票

除了Tim所说的,许多数据库驱动程序使用“连接池”来通过重用旧连接来提高连接性能。所以当Dispose被称为连接时,它们并不真正关闭(除非满足某些条件),但它们在后续调用时保持空闲状态。

https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/connection-pooling


1
投票

为什么不为所有查询使用1个连接?

我认为这将是一个更优雅的解决方案。

void Main()
{
    List<X> listX;
    List<Y> listY;
    List<Z> listZ;
    using(SqlConnection conn = new SqlConnection())
    {
        conn.Open();
        listX=new X().GetParameterListByID(conn, pID);
        listY=new Y().GetParameterListByID(conn, pID);
        listZ=new Z().GetParameterListByID(conn, pID);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.