/// <summary> /// Register connection /// </summary> private void RegisterConnection(LockableSQLiteConnection conn) { List <LockableSQLiteConnection> connections = this.GetOrRegisterConnections(conn.DatabasePath); lock (s_lockObject) { connections.Add(conn); this.m_connectionPool.Remove(conn); // Just in-case // Lock this connection so I know if I can bypass later Monitor.Enter(conn); this.m_tracer.TraceVerbose("++ {0} ({1})", conn.DatabasePath, connections.Count); } }
/// <summary> /// Unregister connection /// </summary> private void UnregisterConnection(LockableSQLiteConnection conn) { List <LockableSQLiteConnection> connections = this.GetOrRegisterConnections(conn.DatabasePath); lock (s_lockObject) { Monitor.Exit(conn); connections.Remove(conn); // Add connection back onto the pool if (conn.Persistent) { this.m_connectionPool.Add(conn); } this.m_tracer.TraceVerbose("-- {0} ({1})", conn.DatabasePath, connections.Count); } }
/// <summary> /// Get or create a pooled connection /// </summary> private LockableSQLiteConnection GetOrCreatePooledConnection(string dataSource, bool isReadonly) { // First is there a connection already? var connections = this.GetOrRegisterConnections(dataSource); WriteableSQLiteConnection writeConnection = null; lock (s_lockObject) { if (this.m_writeConnections.TryGetValue(dataSource, out writeConnection)) { if (Monitor.IsEntered(writeConnection)) { return(writeConnection); } } var conn = connections.FirstOrDefault(o => Monitor.IsEntered(o)); if (conn != null) { return(conn); } } ISQLitePlatform platform = ApplicationContext.Current.GetService <ISQLitePlatform>(); lock (s_lockObject) { LockableSQLiteConnection retVal = null; if (isReadonly) { retVal = this.m_connectionPool.OfType <ReadonlySQLiteConnection>().FirstOrDefault(o => o.DatabasePath == dataSource); } else { if (!this.m_writeConnections.TryGetValue(dataSource, out writeConnection)) // Writeable connection can only have one in the pool so if it isn't there make sure it isn't in the current { writeConnection = new WriteableSQLiteConnection(platform, dataSource, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.FullMutex | SQLiteOpenFlags.Create) { Persistent = true }; writeConnection.Execute("PRAGMA synchronous = 1"); //writeConnection.Execute("PRAGMA automatic_index = true"); //writeConnection.Execute("PRAGMA journal_mode = WAL"); this.m_writeConnections.Add(dataSource, writeConnection); } retVal = writeConnection; } // Remove return value if (retVal != null) { this.m_connectionPool.Remove(retVal); } else if (isReadonly) { retVal = new ReadonlySQLiteConnection(platform, dataSource, SQLiteOpenFlags.ReadOnly | SQLiteOpenFlags.FullMutex) { Persistent = true }; //retVal.Execute("PRAGMA threads = 2"); } else { throw new InvalidOperationException("Should not be here"); } return(retVal); } }