SqliteShrinkMemoryTimer.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using MediaBrowser.Model.Logging;
  2. using System;
  3. using System.Data;
  4. using System.Threading;
  5. namespace MediaBrowser.Server.Implementations.Persistence
  6. {
  7. class SqliteShrinkMemoryTimer : IDisposable
  8. {
  9. private Timer _shrinkMemoryTimer;
  10. private readonly SemaphoreSlim _writeLock;
  11. private readonly ILogger _logger;
  12. private readonly IDbConnection _connection;
  13. public SqliteShrinkMemoryTimer(IDbConnection connection, SemaphoreSlim writeLock, ILogger logger)
  14. {
  15. _connection = connection;
  16. _writeLock = writeLock;
  17. _logger = logger;
  18. _shrinkMemoryTimer = new Timer(TimerCallback, null, TimeSpan.FromMinutes(30), TimeSpan.FromMinutes(30));
  19. }
  20. private async void TimerCallback(object state)
  21. {
  22. await _writeLock.WaitAsync(CancellationToken.None).ConfigureAwait(false);
  23. IDbTransaction transaction = null;
  24. try
  25. {
  26. transaction = _connection.BeginTransaction();
  27. using (var cmd = _connection.CreateCommand())
  28. {
  29. cmd.Transaction = transaction;
  30. cmd.CommandText = "pragma shrink_memory";
  31. cmd.ExecuteNonQuery();
  32. }
  33. transaction.Commit();
  34. }
  35. catch (OperationCanceledException)
  36. {
  37. if (transaction != null)
  38. {
  39. transaction.Rollback();
  40. }
  41. throw;
  42. }
  43. catch (Exception e)
  44. {
  45. _logger.ErrorException("Failed to save items:", e);
  46. if (transaction != null)
  47. {
  48. transaction.Rollback();
  49. }
  50. throw;
  51. }
  52. finally
  53. {
  54. if (transaction != null)
  55. {
  56. transaction.Dispose();
  57. }
  58. _writeLock.Release();
  59. }
  60. }
  61. public void Dispose()
  62. {
  63. if (_shrinkMemoryTimer != null)
  64. {
  65. _shrinkMemoryTimer.Dispose();
  66. _shrinkMemoryTimer = null;
  67. }
  68. }
  69. }
  70. }