private Task SetTitleBarColorsAsync()
 {
     return(_dispatcher.ExecuteAsync(() =>
     {
         var theme = Application.Current.RequestedTheme == ApplicationTheme.Light ? ElementTheme.Light : ElementTheme.Dark;
         ContrastHelper.SetTitleBarButtonsForTheme(theme);
     }));
 }
        private async Task Loop()
        {
            while (true)
            {
                TimeSpan delay;
                var      param = default(T);
                CancellationTokenSource       cts;
                TaskCompletionSource <object> tcs = null;

                lock (_lock)
                {
                    cts = _cts;

                    if (cts?.IsCancellationRequested ?? true)
                    {
                        _tcs?.TrySetCanceled();
                        _tcs = null;
                        return;
                    }

                    delay = _executionTime.Subtract(DateTime.UtcNow);

                    // To avoid waiting for only few milliseconds we're using some threshold
                    if (delay.TotalMilliseconds < DelayThresholdMilliseconds)
                    {
                        param = _param;

                        _cts?.Dispose();
                        _cts = cts = null;
                        tcs  = _tcs;
                        _tcs = null;
                    }
                }

                if (cts == null)
                {
                    if (_dispatcher == null)
                    {
                        _action(param);
                    }
                    else
                    {
                        await _dispatcher.ExecuteAsync(() => _action(param)).ConfigureAwait(false);
                    }

                    tcs?.TrySetResult(null);

                    return;
                }

                try
                {
                    await Task.Delay(delay, cts.Token).ConfigureAwait(false);
                }
                catch
                {
                    // Canceled
                    break;
                }
            }
        }