AvaloniaSynchronizationContext.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using System.Threading;
  9. namespace Avalonia.Threading
  10. {
  11. /// <summary>
  12. /// SynchronizationContext to be used on main thread
  13. /// </summary>
  14. public class AvaloniaSynchronizationContext : SynchronizationContext
  15. {
  16. /// <summary>
  17. /// Controls if SynchronizationContext should be installed in InstallIfNeeded. Used by Designer.
  18. /// </summary>
  19. public static bool AutoInstall { get; set; } = true;
  20. /// <summary>
  21. /// Installs synchronization context in current thread
  22. /// </summary>
  23. public static void InstallIfNeeded()
  24. {
  25. if (!AutoInstall || Current is AvaloniaSynchronizationContext)
  26. {
  27. return;
  28. }
  29. SetSynchronizationContext(new AvaloniaSynchronizationContext());
  30. }
  31. /// <inheritdoc/>
  32. public override void Post(SendOrPostCallback d, object state)
  33. {
  34. Dispatcher.UIThread.InvokeAsync(() => d(state), DispatcherPriority.Send);
  35. }
  36. /// <inheritdoc/>
  37. public override void Send(SendOrPostCallback d, object state)
  38. {
  39. if (Dispatcher.UIThread.CheckAccess())
  40. d(state);
  41. else
  42. Dispatcher.UIThread.InvokeTaskAsync(() => d(state), DispatcherPriority.Send).Wait();
  43. }
  44. }
  45. }