我写的一些代码有一个奇怪的并发问题。首先要问的是为什么我使用CF并使用DbModelBuilder ......我有这样的情况,我可以拥有第N个数据库,这些数据库都是相同的,我必须保持数据的分离。我正在使用CF来防止大型模型生成问题,多个开发人员使用他们的GUI来模仿我的模型。唉,这是我正在做的事情的基本代码。
两个控制台的书写线永远不会被击中,但它们是。
请你试试这个,让我知道问题出在哪里?
这是Test Harness控制台应用程序:
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 100; i++)
{
var workerObject = new Worker();
var workerThread = new Thread(workerObject.DoWork);
workerThread.Start();
}
}
}
public class Worker
{
public void DoWork()
{
var connections = new List<KeyValuePair<string, DynamicDb>>
{
new KeyValuePair<string, DynamicDb>("db1", new MyDynamicEntityLayer("db1").DynamicDb()),
new KeyValuePair<string, DynamicDb>("db2", new MyDynamicEntityLayer("db2").DynamicDb())
};
foreach (var db in connections)
{
if (db.Key == "db1" && db.Value.ConnectionString.Contains("db2"))
Console.WriteLine("THIS SHOULD NEVER HAPPEN!!! db1 : " + db.Value.ConnectionString);
if (db.Key == "db2" && db.Value.ConnectionString.Contains("db1"))
Console.WriteLine("THIS SHOULD NEVER HAPPEN!!! db2 : " + db.Value.ConnectionString);
}
}
}
这是实体类:
public class MyDynamicEntityLayer
{
public static string ConnectionString { get; set; }
public MyDynamicEntityLayer(string db = null)
{
MakeAConnectionString(db);
Database.SetInitializer<DynamicDb>(null);
}
public void MakeAConnectionString(string db)
{
var sqlBuilder = new SqlConnectionStringBuilder();
if (db == "db1")
{
sqlBuilder.DataSource = "MySqlServer";
sqlBuilder.InitialCatalog = "db1";
sqlBuilder.ConnectTimeout = 180;
sqlBuilder.IntegratedSecurity = true;
}
else
{
sqlBuilder.DataSource = "MySqlServer";
sqlBuilder.InitialCatalog = "db2";
sqlBuilder.ConnectTimeout = 180;
sqlBuilder.IntegratedSecurity = true;
}
ConnectionString = sqlBuilder.ToString();
}
public DynamicDb DynamicDb()
{
var builder = new DbModelBuilder(DbModelBuilderVersion.Latest);
TableMappingToBuilder(builder);
var compiled = builder.Build(Database.DefaultConnectionFactory.CreateConnection(ConnectionString)).Compile();
return new DynamicDb(compiled);
}
public void TableMappingToBuilder(DbModelBuilder builder)
{
builder.Configurations.Add(new EntityTypeConfiguration<ConcurrencyTest>());
builder.Entity<ConcurrencyTest>().ToTable("ConcurrencyTest", "dbo");
}
}
和我的DbContext CS文件:
public class DynamicDb : DbContext
{
public string ConnectionString { get; set; }
public DynamicDb(DbCompiledModel model)
: base(MyDynamicEntityLayer.ConnectionString, model)
{
ConnectionString = MyDynamicEntityLayer.ConnectionString;
((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 100;
}
public DbSet<ConcurrencyTest> ConcurrencyTests { get; set; }
}
public class ConcurrencyTest
{
public int ID { get; set; }
public string MyColumn { get; set; }
}
答案 0 :(得分:1)
您的问题是:
public class MyDynamicEntityLayer
{
public static string ConnectionString { get; set; } // STATIC PROPERTY
...
}
所有工作线程共享存储在此属性中的单个值,并为其修改进行争夺。