Database is locked after encryption

Database opened in WAL mode. I get an odd error Database is locked when trying to detach the database backup. The following code is executed on a different thread.

ATTACH DATABASE ‘filename’ AS backup KEY ‘key’;
SELECT sqlcipher_export(‘backup’);
PRAGMA backup.user_version = 23;

// error on this line “database is locked”
DETACH DATABASE backup;

On the UI thread the main database maybe being queried with a large SELECT statement but from my understanding this should not cause a lock.

So why is the database locked after I have exproted an encrypted database?

@mtissington are you using different/independent database handles on each thread, or a single database handle that is shared between two threads?

I’m using c# System.SQLite.NET to create connections which are shared between threads.

@mtissington Since you are sharing connections between threads the most likely explanation is that, when serialized the activities in the UI thread are starting a transaction and the export thread is trying to detach while the transaction is running. It is not possible to attach or detach while in a transaction. If that is the case you could either use separate connections (i.e. one connection for your UI thread, a separate connection to he same database on your export thread), or you could establish a lock to prevent the connection from being used on the UI thread while the export is running.