我有类似于以下代码.
class MyController
{
[ThreadStatic] private DbInterface db;
public void ImportAllData()
{
using (db = new DbInterface())
{
var records = PullData();
PushData(records);
}
}
private DbRecord[] PullData()
{
return db.GetFromTableA();
}
private void PushData(DbRecord[] records)
{
db.InsertIntoTableB(records);
}
}
替代方案是更加麻烦维护.
class MyController
{
public void ImportAllData()
{
using (var db = new DbInterface())
{
var records = PullData(db);
PushData(records,db);
}
}
private DbRecord[] PullData(DbInterface db)
{
return db.GetFromTableA();
}
private void PushData(DbRecord[] records,DbInterface db)
{
db.InsertIntoTableB(records);
}
}
据我所见,我的第一个实现:
>是线程安全的(假设DbInterface是线程安全的),
>阻止任何其他进程触摸db变量,
>确保db将始终处理,即使在异常.
在具有类范围的变量上使用using语句是不好的做法吗?我错过了什么吗?
解决方法
就个人而言,我更喜欢你的第二个选择.
第一个设计的问题是您有效地添加了不必要的设计耦合.您的PullData和PushData方法无法单独使用 – 它们要求首先调用ImportAllData或将设置并正确清除db变量的其他方法.
第二个选项,虽然稍微多一些代码(尽管不是很多),但使每个方法的意图都非常清楚.每个方法都知道它需要在传递给它的外部DbInterface实例上工作.今后几乎没有机会被滥用.