2
2
{
3
3
using EasyCaching . Core ;
4
4
using Microsoft . Data . Sqlite ;
5
- using Microsoft . Extensions . Options ;
5
+ using System . Collections . Concurrent ;
6
+ using System . Data ;
7
+ using System . Threading ;
8
+ using System . Threading . Tasks ;
6
9
7
10
/// <summary>
8
11
/// SQLite database provider.
@@ -16,16 +19,27 @@ public class SQLiteDatabaseProvider : ISQLiteDatabaseProvider
16
19
17
20
public SQLiteDatabaseProvider ( string name , SQLiteOptions options )
18
21
{
19
- this . _name = name ;
20
- this . _options = options . DBConfig ;
22
+ _name = name ;
23
+ _options = options . DBConfig ;
24
+ _builder = new SqliteConnectionStringBuilder
25
+ {
26
+ DataSource = _options . DataSource ,
27
+ Mode = _options . OpenMode ,
28
+ Cache = _options . CacheMode
29
+ } ;
30
+
31
+ _conns = new ConcurrentDictionary < int , SqliteConnection > ( ) ;
21
32
}
22
33
34
+ private static ConcurrentDictionary < int , SqliteConnection > _conns ;
35
+
23
36
/// <summary>
24
- /// The conn.
37
+ /// The builder
25
38
/// </summary>
26
- private static SqliteConnection _conn ;
39
+ private static SqliteConnectionStringBuilder _builder ;
27
40
28
41
private readonly string _name = EasyCachingConstValue . DefaultSQLiteName ;
42
+
29
43
public string DBProviderName => _name ;
30
44
31
45
/// <summary>
@@ -34,19 +48,25 @@ public SQLiteDatabaseProvider(string name , SQLiteOptions options)
34
48
/// <returns>The connection.</returns>
35
49
public SqliteConnection GetConnection ( )
36
50
{
37
- if ( _conn == null )
51
+ var threadId = Thread . CurrentThread . ManagedThreadId ;
52
+ var con = _conns . GetOrAdd ( threadId , CreateNewConnection ( ) ) ;
53
+
54
+ Task . Run ( async ( ) =>
38
55
{
39
- SqliteConnectionStringBuilder builder = new SqliteConnectionStringBuilder ( )
56
+ await Task . Delay ( 5000 ) . ConfigureAwait ( false ) ;
57
+ _conns . TryRemove ( threadId , out var removingConn ) ;
58
+ if ( removingConn ? . State == ConnectionState . Closed )
40
59
{
41
- DataSource = _options . DataSource ,
42
- Mode = _options . OpenMode ,
43
- Cache = _options . CacheMode
44
- } ;
60
+ removingConn . Dispose ( ) ;
61
+ }
62
+ } ) ;
45
63
46
- _conn = new SqliteConnection ( builder . ToString ( ) ) ;
64
+ return con ;
65
+ }
47
66
48
- }
49
- return _conn ;
67
+ private SqliteConnection CreateNewConnection ( )
68
+ {
69
+ return new SqliteConnection ( _builder . ToString ( ) ) ;
50
70
}
51
71
}
52
72
}
0 commit comments