在意外的时间调用了一个方法,当时 运行 一个计时器

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

我有以下问题,我正在 运行 设置定时器 (SetTimer),它应该在经过时 运行 下一个函数 (OnTimedEvent)。

但是,当它应该 运行 时,它失败了,并在“CoreDispatch”上出现“在意外时间调用了一个方法”错误。

我已经尝试寻找解决方案,我想我明白是什么导致了它,但我不确定如何解决它。

希望你们中的一些人能对我的问题有所了解。

         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);
                }
                );
            
        }

在 UI 线程上调用 DispatcherQueue.GetForCurrentThread 以获得 DispatcherQueue,然后使用它来排队调度程序工作:

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);
    });
}

或使用 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...
}