1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Threading;
- using System.Data;
- using System.Diagnostics;
- using System.Data.SQLite;
-
- namespace RDH.PharmacyPlatform.Sync.Core
- {
- internal class ConnectionSessionFactory
- {
- private static Object _lock;
- private static Dictionary<Int32, IDbConnection> _cachedConnectionSessions;
- private ConnectionSessionFactory()
- {
- }
- static ConnectionSessionFactory()
- {
- _lock = new object();
- _cachedConnectionSessions = new Dictionary<int, IDbConnection>();
- }
- public static IDbConnection CreateConnection(String connString)
- {
- //Debug.WriteLine($"CreateConnection start, tid:{Thread.CurrentThread.ManagedThreadId}");
- IDbConnection connection = null;
- lock (_lock)
- {
- if (_cachedConnectionSessions.ContainsKey(Thread.CurrentThread.ManagedThreadId))
- {
- connection = _cachedConnectionSessions[Thread.CurrentThread.ManagedThreadId];
- }
- else
- {
- connection = new SQLiteConnection();
- _cachedConnectionSessions.Add(Thread.CurrentThread.ManagedThreadId, connection);
- connection.ConnectionString = connString;
- connection.Open();
- }
- }
- //Debug.WriteLine("CreateConnection end");
- return connection;
- }
- public static IDbConnection GetConnection()
- {
- //Debug.WriteLine($"GetConnection start, tid:{Thread.CurrentThread.ManagedThreadId}");
- IDbConnection conn = null;
- lock (_lock)
- {
- if (_cachedConnectionSessions.ContainsKey(Thread.CurrentThread.ManagedThreadId))
- {
- conn = _cachedConnectionSessions[Thread.CurrentThread.ManagedThreadId];
- }
- }
- return conn;
- }
- public static void CloseConnection()
- {
- //Debug.WriteLine($"CloseConnection start, tid:{Thread.CurrentThread.ManagedThreadId}");
- lock (_lock)
- {
- if (_cachedConnectionSessions.ContainsKey(Thread.CurrentThread.ManagedThreadId))
- {
- IDbConnection conn = _cachedConnectionSessions[Thread.CurrentThread.ManagedThreadId];
- conn.Close();
- conn.Dispose();
- _cachedConnectionSessions.Remove(Thread.CurrentThread.ManagedThreadId);
- }
- }
- }
- }
- }
|