WeakEventTests.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using Avalonia.Utilities;
  7. using Xunit;
  8. namespace Avalonia.Base.UnitTests
  9. {
  10. public class WeakEventTests
  11. {
  12. class EventSource
  13. {
  14. public event EventHandler Event;
  15. public void Fire()
  16. {
  17. Event?.Invoke(this, new EventArgs());
  18. }
  19. public static readonly WeakEvent<EventSource, EventArgs> WeakEv = WeakEvent.Register<EventSource>(
  20. (t, s) => t.Event += s,
  21. (t, s) => t.Event -= s);
  22. }
  23. class Subscriber : IWeakEventSubscriber<EventArgs>
  24. {
  25. private readonly Action _onEvent;
  26. public Subscriber(Action onEvent)
  27. {
  28. _onEvent = onEvent;
  29. }
  30. public void OnEvent(object sender, WeakEvent ev, EventArgs args)
  31. {
  32. _onEvent?.Invoke();
  33. }
  34. }
  35. [Fact]
  36. public void EventShouldBePassedToSubscriber()
  37. {
  38. bool handled = false;
  39. var subscriber = new Subscriber(() => handled = true);
  40. var source = new EventSource();
  41. EventSource.WeakEv.Subscribe(source, subscriber);
  42. source.Fire();
  43. Assert.True(handled);
  44. }
  45. [Fact]
  46. public void EventHandlerShouldNotBeKeptAlive()
  47. {
  48. bool handled = false;
  49. var source = new EventSource();
  50. AddSubscriber(source, () => handled = true);
  51. for (int c = 0; c < 10; c++)
  52. {
  53. GC.Collect();
  54. GC.Collect(3, GCCollectionMode.Forced, true);
  55. }
  56. source.Fire();
  57. Assert.False(handled);
  58. }
  59. private static void AddSubscriber(EventSource source, Action func)
  60. {
  61. EventSource.WeakEv.Subscribe(source, new Subscriber(func));
  62. }
  63. }
  64. }