PetaPoco Transaction in Multithreaded Env

I am just testing a PetaPoco transaction in a multi-threaded way ...

I have a simple test case:

- The simple value object is called MediaDevice - Insert the update record 1000 times

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);

}

And I call it in two threads as follows: [Single Database object for both threads]

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()

}

I get a Null error or sometimes an object located for the database ..

But when I put two database instances,

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()

}

Everthing OK ...

Good. When I check the source code of PetaPoco in a transaction, I see that in a transaction. Full featured

 public virtual void Complete()
        {
            _db.CompleteTransaction();
            _db = null;
        }

My question is the ability to use a transaction from multiple threads. Should I use a new copy of the database object? Or what am I doing wrong?

, ?

+5
3

, PetaPoco. . PetaPoco:

: PetaPoco. , , per-http IOC . StructureMap - .

, . , PetaPoco .

+4

, nolock select query, . long count = db.ExecuteScalar( "SELECT Count (*) nolock FROM MediaDevices" );

+1

Sorry dude. Yes you are right. they change the object to zero. therefore, you cannot use the same object for streaming processing. you should use them described as db = GetDataBase (); db2 = GetDataBase ();

otherwise, you can change the source code for your requirement. I think their license allows this. but I'm not sure.

+1
source

All Articles