希望您能帮助我弄清对线程安全和引用类型的多个实例的理解。
我在下面概述了一个简单的情况。我的问题是:如果ProcessorOne和ProcessorTwo同时运行,并且DatabaseIntegration类是引用类型,并且ProcessorOne和ProcessorTwo都有自己的DataBaseIntegration实例,那么ProcessorOne保存的实体是否具有名称的可能性来自ProcessorTwo的阻止?
public class ProcessorOne
{
private readonly DatabaseIntegration databaseIntegration;
public ProcessorOne(DatabaseIntegration databaseIntegration)
{
this.databaseIntegration = databaseIntegration;
}
public void Process()
{
this.databaseIntegration.SetName("NameOne")
Entity entity = new Entity()
this.dataBaseIntegration.Save(entity);
}
}
public class ProcessorTwo
{
private readonly DatabaseIntegration dataBaseIntegration;
public ProcessorTwo(DatabaseIntegration dataBaseIntegration)
{
this.dataBaseIntegration = dataBaseIntegration;
}
public void Process()
{
this.databaseIntegration.SetName("NameTwo")
Entity entity = new Entity()
this.dataBaseIntegration.Save(entity);
}
}
public class DatabaseIntegration
{
private string entityName;
public void SetName(string entityName)
{
this.entityName = entityName;
}
public void Save(Entity entity)
{
entity.EntityName = this.entityName;
using (DbContext context = new DbContext(sqlConnection))
{
context.Entity.Add(entity);
context.SaveChanges();
}
}
}
答案 0 :(得分:2)
不,它们将具有不同的名称,因为正如您所说,在您的代码中,每个类都有一个不同的DatabaseIntegration实例。
所以ProcessorOne的dataBaseIntegration名称为“ NameOne”,ProcessorTwo的dataBaseIntegration名称为“ NameTwo”。
致谢。
答案 1 :(得分:1)
回答是的,它们是线程安全的。但是,为什么在创建实体名称时不设置实体名称。在那种情况下,即使您使用相同的DatabaseIntegration对象,它仍然是线程安全的,因为每次调用Save()时,您都传递不同的实体对象。
public class ProcessorOne
{
private readonly DatabaseIntegration databaseIntegration;
public ProcessorOne(DatabaseIntegration databaseIntegration)
{
this.databaseIntegration = databaseIntegration;
}
public void Process()
{
Entity entity = new Entity(){entityName = "NameOne"}
this.dataBaseIntegration.Save(entity);
}
}
public class ProcessorTwo
{
private readonly DatabaseIntegration dataBaseIntegration;
public ProcessorTwo(DatabaseIntegration dataBaseIntegration)
{
this.dataBaseIntegration = dataBaseIntegration;
}
public void Process()
{
Entity entity = new Entity(){entityName = "NameTwo"}
this.dataBaseIntegration.Save(entity);
}
}
public class DatabaseIntegration
{
public void Save(Entity entity)
{
using (DbContext context = new DbContext(sqlConnection))
{
context.Entity.Add(entity);
context.SaveChanges();
}
}
}