锁定类成员还是在类的方法中初始化该对象?



所以,我有这个服务,我们称之为"MyService"。MyService有一个公共方法,就是"executeBatchJob",顾名思义,它会执行一个batchJob,总之就是从数据库中检索一些数据,在某些时候,我有一个非常像实体的对象,有一个ID和一个记录列表。在我的方法 executeBatchJob 中,会进行一些检查,当满足某些条件时,实体被写入某处并重新初始化(新 ID,不同的记录(,但请注意,它发生在 executeBatchJob 调用的私有方法中。在其他条件下,在不同的私有方法中,记录被添加到实体持有的记录列表中。

我的问题是:由于服务可能由多个进程调用:将该实体声明为类成员(私有只读(并在需要时锁定它是否更好,然后有一个方法可以清理实体的状态下一个进程。还是在我的方法 executeBatchJob 中声明和使用这个对象更好,但是通过所有私有方法拖动对象,因为对象的状态可以在几个"级别"发生变化?

为了说明我在解释什么:

这是我的实体:

public class MyEntity
{
public int Id { get; set; }
public List<Record> Records { get;  set; }
public void CleanUp(int newId)
{
Id = newId;
Records.Clear();
}
}

这是带锁的我的服务:

public class MyService : IMyService
{
private readonly MyEntity _myEntity;
public MyService()
{
_myEntity = new MyEntity();
}
public void executeBatchJob(int batchId)
{
//some code
lock(_myEntity)
{
// More code and call to some private method
_myEntity.CleanUp();
}
// still more code
}
}

或者使用第二个选项:

public class MyService : IMyService
{
public MyService()
{
}
public void executeBatchJob(int batchId)
{
MyEntity myEntity = new MyEntity();
APrivateMethodInExecuteBatchJob(myEntity);
// more code
}
private returnResult APrivateMethodInExecuteBatchJob(MyEntity myEntity)
{
// Some manipulation of myEntity
// some code, with another call to a private method with myEntity, and manipulation of myEntity
// ... write the entity
myRepository.write(myEntity);
}
}

为了提供更多上下文,据我所知,每次编写实体时,都必须对其进行清理,在第二个选项中,我可以做一个"new MyEntity(("(从业务角度来看更有意义(。

对我来说,第二种解决方案更合乎逻辑和更合适,但是,我将有几个私有方法可以移动对象,有时只是将其传递给另一个私有方法,除了将其"传递"到另一个私有方法之外,没有任何其他操作......这根本不干净...

这就是为什么我需要你的建议/意见。

使用IDisposable界面,它的目的正是您正在做的事情

public class MyEntity: IDisposable;

然后,您可以使用带有 using 关键字的第二个选项。

您可以在此处查看有关实现内容和方式的示例。 https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose

代码示例:

public void executeBatchJob(int batchId)
{
using (vMyEntity myEntity = new MyEntity();) 
{
APrivateMethodInExecuteBatchJob(myEntity);
// more code
}
}

通常,尽量避免在不需要时使用锁。它可能会产生争用条件,使应用程序的响应速度降低。

如果实体不应该保持其状态,在我看来,使用选项 2 中的幂等方法要好得多。如果你能使方法静态,你最终会得到一个更简单的架构。

正如您已经确定的那样,您将遇到需要将资源锁定在选项 1 中的问题,只要在清理期间丢弃状态,就没有必要感到头疼。

我可以看到类似选项 1 的唯一原因是,如果实体是从两次使用之间未清除的交易构建的,或者如果由于某种原因创建实体非常昂贵。

最新更新