C# UWP 如何在每个时间间隔触发一个方法?

C# UWP how to trigger a method every interval?

我目前正在尝试制作一个计时器的动画,以显示应用 运行 已运行了多长时间。

_timerThread = new Thread(_textBlockTimer.CounterStart);
_timerThread.IsBackground = true;
_timerThread.SetApartmentState(System.Threading.ApartmentState.STA);
_timerThread.Start();

定时器 class 看起来像这样:

class Timer {
    private TextBlock _timeTextBlock;
    private bool _timing = false;
    private int _timer = 0;
    public Timer(TextBlock timeTextBlock) {
        _timeTextBlock = timeTextBlock;

    }

    public void CounterStart() {
        _timing = true;
        while (_timing) {
            Thread.Sleep(1000);
            int time = _timer++;
            _timerTextBlock.Text = time.ToString();
        }
    }
}

执行此操作后,出现以下错误:

System.Exception: 'The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))'

这让我觉得可以让这个任务成为同一个界面的一部分?

有没有另一种方法可以简单地 运行 一个方法,而不用暂停一切等待方法完成?在这种情况下不会发生这种情况,因为它应该连续向上计数。

此致,

The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))'

问题是您在non-uithread中更新了界面,为了在UWP中每隔一段时间触发一个方法,我们建议您使用DispatcherTimer来替换。

var timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += Timer_Tick;
timer.Start();


int _timer = 0;
private void Timer_Tick(object sender, object e)
{
    int time = _timer++;
    _timeTextBlock.Text = time.ToString();
}