电子药箱通讯服务端
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

ConnectionSessionFactory.cs 2.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Threading;
  7. using System.Data;
  8. using System.Diagnostics;
  9. using System.Data.SQLite;
  10. namespace RDH.PharmacyPlatform.Sync.Core
  11. {
  12. internal class ConnectionSessionFactory
  13. {
  14. private static Object _lock;
  15. private static Dictionary<Int32, IDbConnection> _cachedConnectionSessions;
  16. private ConnectionSessionFactory()
  17. {
  18. }
  19. static ConnectionSessionFactory()
  20. {
  21. _lock = new object();
  22. _cachedConnectionSessions = new Dictionary<int, IDbConnection>();
  23. }
  24. public static IDbConnection CreateConnection(String connString)
  25. {
  26. //Debug.WriteLine($"CreateConnection start, tid:{Thread.CurrentThread.ManagedThreadId}");
  27. IDbConnection connection = null;
  28. lock (_lock)
  29. {
  30. if (_cachedConnectionSessions.ContainsKey(Thread.CurrentThread.ManagedThreadId))
  31. {
  32. connection = _cachedConnectionSessions[Thread.CurrentThread.ManagedThreadId];
  33. }
  34. else
  35. {
  36. connection = new SQLiteConnection();
  37. _cachedConnectionSessions.Add(Thread.CurrentThread.ManagedThreadId, connection);
  38. connection.ConnectionString = connString;
  39. connection.Open();
  40. }
  41. }
  42. //Debug.WriteLine("CreateConnection end");
  43. return connection;
  44. }
  45. public static IDbConnection GetConnection()
  46. {
  47. //Debug.WriteLine($"GetConnection start, tid:{Thread.CurrentThread.ManagedThreadId}");
  48. IDbConnection conn = null;
  49. lock (_lock)
  50. {
  51. if (_cachedConnectionSessions.ContainsKey(Thread.CurrentThread.ManagedThreadId))
  52. {
  53. conn = _cachedConnectionSessions[Thread.CurrentThread.ManagedThreadId];
  54. }
  55. }
  56. return conn;
  57. }
  58. public static void CloseConnection()
  59. {
  60. //Debug.WriteLine($"CloseConnection start, tid:{Thread.CurrentThread.ManagedThreadId}");
  61. lock (_lock)
  62. {
  63. if (_cachedConnectionSessions.ContainsKey(Thread.CurrentThread.ManagedThreadId))
  64. {
  65. IDbConnection conn = _cachedConnectionSessions[Thread.CurrentThread.ManagedThreadId];
  66. conn.Close();
  67. conn.Dispose();
  68. _cachedConnectionSessions.Remove(Thread.CurrentThread.ManagedThreadId);
  69. }
  70. }
  71. }
  72. }
  73. }