UnitTestSynchronizationContext.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright (c) The Avalonia Project. All rights reserved.
  2. // Licensed under the MIT license. See licence.md file in the project root for full license information.
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Reactive.Disposables;
  6. using System.Threading;
  7. namespace Avalonia.Base.UnitTests.Data
  8. {
  9. internal sealed class UnitTestSynchronizationContext : SynchronizationContext
  10. {
  11. readonly List<Tuple<SendOrPostCallback, object>> _postedCallbacks =
  12. new List<Tuple<SendOrPostCallback, object>>();
  13. public static Scope Begin()
  14. {
  15. var sync = new UnitTestSynchronizationContext();
  16. var old = SynchronizationContext.Current;
  17. SynchronizationContext.SetSynchronizationContext(sync);
  18. return new Scope(old, sync);
  19. }
  20. public override void Send(SendOrPostCallback d, object state)
  21. {
  22. d(state);
  23. }
  24. public override void Post(SendOrPostCallback d, object state)
  25. {
  26. lock (_postedCallbacks)
  27. {
  28. _postedCallbacks.Add(Tuple.Create(d, state));
  29. }
  30. }
  31. public void ExecutePostedCallbacks()
  32. {
  33. lock (_postedCallbacks)
  34. {
  35. _postedCallbacks.ForEach(t => t.Item1(t.Item2));
  36. _postedCallbacks.Clear();
  37. }
  38. }
  39. public class Scope : IDisposable
  40. {
  41. private readonly SynchronizationContext _old;
  42. private readonly UnitTestSynchronizationContext _new;
  43. public Scope(SynchronizationContext old, UnitTestSynchronizationContext n)
  44. {
  45. _old = old;
  46. _new = n;
  47. }
  48. public void Dispose()
  49. {
  50. SynchronizationContext.SetSynchronizationContext(_old);
  51. }
  52. public void ExecutePostedCallbacks()
  53. {
  54. _new.ExecutePostedCallbacks();
  55. }
  56. }
  57. }
  58. }