I’m doing some stuff with SQLite, and I want threads to block while I am in a “Transaction”. Will the below code work correctly?
public class ThreadSafeSQLiteConnection
{
private readonly SQLiteConnection connection;
public static object TRANSACTION_LOCK = new Object();
public void BeginTransaction() {
Monitor.Enter(TRANSACTION_LOCK);
connection.BeginTransaction();
}
public void Commit() {
connection.Commit();
Monitor.Exit(TRANSACTION_LOCK);
}
public void Rollback() {
connection.Rollback();
Monitor.Exit(TRANSACTION_LOCK);
}
}
If I have a transaction open in this case, no threads can enter the BeginTransaction method correct?
Yes, the following code will work but it will misbehave when working with multiple connections since your locker instance is static and therefore shared by all instances. I dont see why you would want a statically synchronized locker instance since the sql transaction already provides the synchronization. So: just remove the static part from the transaction_lock and you’re good to go!