WeakEventHandlerManagerTests.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 WeakEventHandlerManagerTests
  11. {
  12. class EventSource
  13. {
  14. public event EventHandler<EventArgs> Event;
  15. public void Fire()
  16. {
  17. Event?.Invoke(this, new EventArgs());
  18. }
  19. }
  20. class Subscriber
  21. {
  22. private readonly Action _onEvent;
  23. public Subscriber(Action onEvent)
  24. {
  25. _onEvent = onEvent;
  26. }
  27. public void OnEvent(object sender, EventArgs ev)
  28. {
  29. _onEvent?.Invoke();
  30. }
  31. }
  32. [Fact]
  33. public void EventShoudBePassedToSubscriber()
  34. {
  35. bool handled = false;
  36. var subscriber = new Subscriber(() => handled = true);
  37. var source = new EventSource();
  38. WeakEventHandlerManager.Subscribe<EventSource, EventArgs, Subscriber>(source, "Event",
  39. subscriber.OnEvent);
  40. source.Fire();
  41. Assert.True(handled);
  42. }
  43. [Fact]
  44. public void EventHandlerShouldNotBeKeptAlive()
  45. {
  46. bool handled = false;
  47. var source = new EventSource();
  48. AddCollectableSubscriber(source, "Event", () => handled = true);
  49. for (int c = 0; c < 10; c++)
  50. {
  51. GC.Collect();
  52. GC.Collect(3, GCCollectionMode.Forced, true);
  53. }
  54. source.Fire();
  55. Assert.False(handled);
  56. }
  57. private void AddCollectableSubscriber(EventSource source, string name, Action func)
  58. {
  59. WeakEventHandlerManager.Subscribe<EventSource, EventArgs, Subscriber>(source, name, new Subscriber(func).OnEvent);
  60. }
  61. }
  62. }