views:

14

answers:

1

Hello.

I have a question. Imagine you'd have an object you'd want to save in a transaction, the object having collections of other objects etc so its a more "complex" object.

Anyway, sometimes we save objects like that, but in the meantime, we use another thread that occasionally reads said data and synchronizes them up to our central server. However we've noticed problems that in some occasions objects get synced over without all the collection objects.

Since this only happens every once in a while we figured it could be the transaction isolation level. Maybe the synchronization thread reads the data before the transaction is done persisting all the objects, thus only reading half the data needed, and sending it over.

Because we all know that the clients data is all saved, all the time, it's just that sometimes it doesn't tag along when it's being sent to us.

So we'd want some kind of lock I suppose, I just don't know anything about these locks. Which one should we use?

There are no outside sources working towards the database in this case, since it's a WPF application on a client's customer.

Any help would be appreciated!

Best regards, E.

+1  A: 

Every database supports a set of standard isolation levels. These are all meant to prevent to a certain level that you read data that is modified inside another transaction. I suggest you first read up on what these isoloation levels mean.

In your specific situation, I'd suggest that for the transaction that is reading the data, you use at least an isolation level of ReadCommitted. In code, this would look like this:

using (var transactionScope = new TransactionScope(TransactionScopeOption.Required,
    new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted }))
{
    // Read the data you want from the database.
    ...
    transactionScope.Complete();
    // Return the data.
}

Using a TransactionScope with IsolationLevel.ReadCommitted prevents that you read data that has not yet been committed by another transaction.

The code that writes data to the database should also be put inside one transaction. As long as you only write data inside that transaction, the isolation level for that transaction doesn't matter. This guarantees the atomicity of your updates: either all updates succeed or none of them. This also prevents another transaction from reading a partial update.

Ronald Wildenberg
Thanks alot mate! Exactly what I needed to know. :)
Einarsson