我只是测试PetaPoco事务在多线程的方式...
我有一个简单的测试案例:
- 简单的值对象称之为MediaDevice - 插入一条记录的更新它的1000倍
void TransactionThread(Object object)
{
Database db = (Database) object;
for(int i= 0; i < 1000;i++)
{
Transaction transaction = db.GetTransaction();
MediaDevice device = new MediaDevice();
device.Name = "Name";
device.Brand = "Brand";
db.Insert(device);
device.Name = "Name_Updated";
device.Brand = "Brand_Updated";
db.Update(device);
transaction.Complete();
}
long count = db.ExecuteScalar<long>("SELECT Count(*) FROM MediaDevices");
Console.WriteLine("Number of all records:" + count);
}
我呼吁这两个线程像这样:两个线程单个数据库对象]
void TransactionTest()
{
Database db = GetDatabase();
Thread tThread1 = ... // thread for TransactionTest()
Thread tThread2 = ... // thread for TransactionTest()
tThread1.Start(db); // pass Database to TransactionTest()
tThread2.Start(db); // pass same Database to TransactionTest()
}
我得到空的错误,有时对象设置错误数据库..
但是,当我提供两个数据库实例,
void TransactionTest()
{
Database db = GetDatabase();
Database db2 = GetDatabase();
Thread tThread1 = ... // thread for TransactionTest()
Thread tThread2 = ... // thread for TransactionTest()
tThread1.Start(db); // pass Database instance db to TransactionTest()
tThread2.Start(db2); // pass Database intance db2 to TransactionTest()
}
寄托都正常...
那么当我在交易检查PetaPoco源代码,我看到,在transaction.Complete
public virtual void Complete()
{
_db.CompleteTransaction();
_db = null;
}
我的问题是,要能够从多个线程我必须使用数据库对象的新副本使用事务? 或者我究竟做错了什么?
并使其线程安全的我一定要打开,并在每个数据更新询问关闭新的数据库?