CefObjectTracker.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace Xilium.CefGlue
  5. {
  6. public static class CefObjectTracker
  7. {
  8. [ThreadStatic]
  9. private static HashSet<IDisposable> _disposables;
  10. private class TrackingSession : IDisposable
  11. {
  12. public static readonly TrackingSession Default = new TrackingSession(stopTracking: true);
  13. public static readonly TrackingSession Nop = new TrackingSession(stopTracking: false);
  14. private readonly bool _stopTracking;
  15. private TrackingSession(bool stopTracking)
  16. {
  17. _stopTracking = stopTracking;
  18. }
  19. public void Dispose()
  20. {
  21. if (_stopTracking)
  22. {
  23. StopTracking();
  24. }
  25. }
  26. }
  27. /// <summary>
  28. /// Starts tracking the objects created on the current thread.
  29. /// </summary>
  30. /// <returns></returns>
  31. public static IDisposable StartTracking()
  32. {
  33. if (_disposables != null)
  34. {
  35. return TrackingSession.Nop; // return a nop session, won't stop tracking, the outer most session should do the job
  36. }
  37. _disposables = new HashSet<IDisposable>();
  38. return TrackingSession.Default;
  39. }
  40. /// <summary>
  41. /// Disposes the objects registered on the current thread since tracker was started.
  42. /// </summary>
  43. public static void StopTracking()
  44. {
  45. if (_disposables == null)
  46. {
  47. return;
  48. }
  49. var disposables = _disposables.ToArray();
  50. _disposables = null; // set null before running dispose to prevent objects running untrack
  51. foreach (var disposable in disposables)
  52. {
  53. disposable.Dispose();
  54. }
  55. }
  56. /// <summary>
  57. /// Registers the specified object to be disposed later.
  58. /// </summary>
  59. /// <param name="obj"></param>
  60. public static void Track(IDisposable obj)
  61. {
  62. if (_disposables != null)
  63. {
  64. _disposables.Add(obj);
  65. }
  66. }
  67. /// <summary>
  68. /// Removes the specified object from the tracking list.
  69. /// </summary>
  70. /// <param name="obj"></param>
  71. public static void Untrack(IDisposable obj)
  72. {
  73. if (_disposables != null)
  74. {
  75. _disposables.Remove(obj);
  76. }
  77. }
  78. }
  79. }