UsageCounter.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /* Copyright (C) 2016 Tal Aloni <tal.aloni.il@gmail.com>. All rights reserved.
  2. *
  3. * You can redistribute this program and/or modify it under the terms of
  4. * the GNU Lesser Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. */
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Text;
  10. using System.Threading;
  11. namespace ISCSIConsole
  12. {
  13. public class UsageCounter
  14. {
  15. private SortedList<string, int> m_targetsInUse = new SortedList<string, int>();
  16. private int m_sessionCount = 0;
  17. public void NotifySessionStart(string targetName)
  18. {
  19. Interlocked.Increment(ref m_sessionCount);
  20. lock (m_targetsInUse)
  21. {
  22. int index = m_targetsInUse.IndexOfKey(targetName);
  23. if (index >= 0)
  24. {
  25. m_targetsInUse[targetName]++;
  26. }
  27. else
  28. {
  29. m_targetsInUse.Add(targetName, 1);
  30. }
  31. }
  32. }
  33. public void NotifySessionTermination(string targetName)
  34. {
  35. Interlocked.Decrement(ref m_sessionCount);
  36. lock (m_targetsInUse)
  37. {
  38. int index = m_targetsInUse.IndexOfKey(targetName);
  39. if (index >= 0)
  40. {
  41. int useCount = m_targetsInUse[targetName];
  42. useCount--;
  43. if (useCount == 0)
  44. {
  45. m_targetsInUse.Remove(targetName);
  46. }
  47. else
  48. {
  49. m_targetsInUse[targetName] = useCount;
  50. }
  51. }
  52. }
  53. }
  54. public bool IsTargetInUse(string targetName)
  55. {
  56. lock (m_targetsInUse)
  57. {
  58. return m_targetsInUse.ContainsKey(targetName);
  59. }
  60. }
  61. public int SessionCount
  62. {
  63. get
  64. {
  65. return m_sessionCount;
  66. }
  67. }
  68. }
  69. }