6
votes

I am creating a System.Data.SQLite in-memory database using connection string as

"Data Source=:memory:", 

and want to access this database among multi-threads.

Now what I do is to clone the SQLiteConnection object and pass the copy to worker threads.

But I found that different threads actually get individual instances of in-memory database, not a shared one. How can I share one in-memory database among threads?

Thanks!

1
There's probably a correct way to do this, but if you in a pinch, you could try using a memory mapped file -- It's a little known feature, but essentially, .NET lets you create a fake file, which just points at an area of memory; then anything that tries to access that file [including external apps, etc.] will actually just be working against memory instead. -- Though, I don't know how well SQLite likes multiple threads talking to the same file at once, they might step on each others' feet and corrupt the file. - BrainSlugs83

1 Answers

6
votes

Based on the SQLite documentation for in-memory databases, I would try a datasource named with URI filename convention file::memory:?cache=shared or the like instead of :memory: (and note specifically the cache name that all connections are being told to use). As explained on the page, every instance of a :memory: is distinct from one another, exactly as you found.

Note you may also have to first enable shared-cache mode before making the connections to the in-memory database (as specified in the shared cache documentation with a call to sqlite3_enable_shared_cache(int) for this to work.