6

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
  • 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. Commented Feb 17, 2017 at 22:21

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Would you happen to know how I can do the same in H2?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.