'A method was called at an unexpected time, when running a timer

I have the following issue, I'm running the timer (SetTimer), and it is supposed to, on elapsed, run the next function (OnTimedEvent).

However, when it is supposed to run, it fails with "A method was called at an unexpected time" error on the "CoreDispatch".

I have tried searching for a solution, and I think I understand what is causing it, but I'm not sure how to fix it.

Hopefully some of you can shed some light on my issue.

         private void SetTimer()
        {
            // Create a timer with a two second interval.
            aTimer = new System.Timers.Timer(RandomNum(1000,2000));
            // Hook up the Elapsed event for the timer. 
            aTimer.Elapsed += OnTimedEvent;
            aTimer.AutoReset = true;
            aTimer.Enabled = true;
        }

         public async void OnTimedEvent(Object source, ElapsedEventArgs e)
        {
            await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                () =>
                {
                    System.Diagnostics.Debug.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
                      e.SignalTime);
                }
                );
            
        }


Solution 1:[1]

Call DispatcherQueue.GetForCurrentThread on the UI thread to get a DispatcherQueue and then use it to enqueue dispatcher work:

readonly DispatcherQueue dispatcherQueue = DispatcherQueue.GetForCurrentThread();

private void SetTimer()
{
    // Create a timer with a two second interval.
    aTimer = new System.Timers.Timer(RandomNum(1000,2000));
    // Hook up the Elapsed event for the timer. 
    aTimer.Elapsed += OnTimedEvent;
    aTimer.AutoReset = true;
    aTimer.Enabled = true;
}

public void OnTimedEvent(Object source, ElapsedEventArgs e)
{
    dispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Normal, () =>
    {
        System.Diagnostics.Debug.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
            e.SignalTime);
    });
}

Or use a DispatcherTimer:

DispatcherTimer aTimer;

private void SetTimer()
{
    aTimer = new DispatcherTimer();
    aTimer.Interval = TimeSpan.FromMilliseconds(RandomNum(1000,2000));
    aTimer.Tick += ATimer_Tick;
    aTimer.Start();
}

private void ATimer_Tick(object sender, object e)
{
    // do something on the UI thread...
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mm8