ThreadTracker.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Text;
  5. using System.Threading;
  6. namespace OpenSim.Framework
  7. {
  8. public static class ThreadTracker
  9. {
  10. public static List<ThreadTrackerItem> m_Threads;
  11. public static System.Threading.Thread ThreadTrackerThread;
  12. private static readonly long ThreadTimeout = 30 * 10000000;
  13. static ThreadTracker()
  14. {
  15. #if DEBUG
  16. m_Threads = new List<ThreadTrackerItem>();
  17. ThreadTrackerThread = new Thread(ThreadTrackerThreadLoop);
  18. ThreadTrackerThread.Name = "ThreadTrackerThread";
  19. ThreadTrackerThread.IsBackground = true;
  20. ThreadTrackerThread.Priority = System.Threading.ThreadPriority.BelowNormal;
  21. ThreadTrackerThread.Start();
  22. #endif
  23. }
  24. private static void ThreadTrackerThreadLoop()
  25. {
  26. while (true)
  27. {
  28. Thread.Sleep(5000);
  29. CleanUp();
  30. }
  31. }
  32. public static void Add(System.Threading.Thread thread)
  33. {
  34. #if DEBUG
  35. lock (m_Threads)
  36. {
  37. ThreadTrackerItem tti = new ThreadTrackerItem();
  38. tti.Thread = thread;
  39. tti.LastSeenActive = DateTime.Now.Ticks;
  40. m_Threads.Add(tti);
  41. }
  42. #endif
  43. }
  44. public static void Remove(System.Threading.Thread thread)
  45. {
  46. #if DEBUG
  47. lock (m_Threads)
  48. {
  49. foreach (ThreadTrackerItem tti in new ArrayList(m_Threads))
  50. {
  51. if (tti.Thread == thread)
  52. m_Threads.Remove(tti);
  53. }
  54. }
  55. #endif
  56. }
  57. public static void CleanUp()
  58. {
  59. lock (m_Threads)
  60. {
  61. foreach (ThreadTrackerItem tti in new ArrayList(m_Threads))
  62. {
  63. if (tti.Thread.IsAlive)
  64. {
  65. // Its active
  66. tti.LastSeenActive = DateTime.Now.Ticks;
  67. }
  68. else
  69. {
  70. // Its not active -- if its expired then remove it
  71. if (tti.LastSeenActive + ThreadTimeout < DateTime.Now.Ticks)
  72. m_Threads.Remove(tti);
  73. }
  74. }
  75. }
  76. }
  77. public static List<Thread> GetThreads()
  78. {
  79. if (m_Threads == null)
  80. return null;
  81. List<Thread> threads = new List<Thread>();
  82. lock (m_Threads)
  83. {
  84. foreach (ThreadTrackerItem tti in new ArrayList(m_Threads))
  85. {
  86. threads.Add(tti.Thread);
  87. }
  88. }
  89. return threads;
  90. }
  91. public class ThreadTrackerItem
  92. {
  93. public System.Threading.Thread Thread;
  94. public long LastSeenActive;
  95. }
  96. }
  97. }