sqliteado.netcontention

sqlite - how can I handle potential contention between two separate threads accessing the same database?


QUESTION: How can I handle potential contention between two separate threads accessing the same Sqlite database?

BACKGROUND: I have a C# Winforms application that uses Sqlite via ADO.net. I do have a backgroundworker thread in the winforms application. I have noticed that I can get an exception when both the main thread, and the background worker thread, attempt to update the sqlite database, i.e. calling a DBDataAdaptor.Update()..

So I'm interested in what checks my code (albeit main thread code &/or code that runs in backgroundworker) to handle this gracefully, either via a way to check beforehand, or blocking until OK, or raising a specific error I can catch...

thanks


Solution

  • In sqlite you can configure a callback that is triggered when you encounter a SQLITE_BUSY or SQLITE_IOERR_BLOCKED error (see http://www.sqlite.org/c3ref/busy_handler.html).

    As most of the time what you'd want to do is sleep and retry the query on busy, sqlite has a built in callback that does exactly that; read up on sqlite3_busy_timeout at http://www.sqlite.org/c3ref/busy_timeout.html.