using System; using System.Runtime.ConstrainedExecution; using System.Threading; namespace Avalonia.Threading { /// /// SynchronizationContext to be used on main thread /// public class AvaloniaSynchronizationContext : SynchronizationContext { /// /// Controls if SynchronizationContext should be installed in InstallIfNeeded. Used by Designer. /// public static bool AutoInstall { get; set; } = true; /// /// Installs synchronization context in current thread /// public static void InstallIfNeeded() { if (!AutoInstall || Current is AvaloniaSynchronizationContext) { return; } SetSynchronizationContext(new AvaloniaSynchronizationContext()); } /// public override void Post(SendOrPostCallback d, object? state) { Dispatcher.UIThread.Post(() => d(state), DispatcherPriority.Background); } /// public override void Send(SendOrPostCallback d, object? state) { if (Dispatcher.UIThread.CheckAccess()) d(state); else Dispatcher.UIThread.InvokeAsync(() => d(state), DispatcherPriority.Send).GetAwaiter().GetResult(); } } }