繁体   English   中英

WPF DispatcherTimer不触发

[英]WPF DispatcherTimer does not fire

我有一个带有RefreshAsync方法的类,该类可能需要很长时间才能执行。 我正在使用Mvvm light框架。 我需要在对象创建后调用它,但不是每次从servicelocator获得实例时都调用它

var vm = ServiceLocator.Current.GetInstance<FileSystemViewModel>();

因此,我使用DispatcherTimer创建延迟更新逻辑。 但这不会触发,我也不知道为什么。

这是代码

private DispatcherTimer _timer;

public FileSystemViewModel()
{
    _timer = new DispatcherTimer(DispatcherPriority.Send) {Interval = TimeSpan.FromMilliseconds(20)};
    _timer.Tick += DefferedUpdate;
    _timer.Start();
}

private async void DefferedUpdate(object sender, EventArgs e)
{
    (sender as DispatcherTimer)?.Stop();
    await RefreshAsync().ConfigureAwait(false);
}

创建DispatcherTimer必须从具有活动Dispatcher的线程完成,或者将活动的分派器传递给计时器的构造函数,例如

new DispatcherTimer(Application.Current.Dispatcher)

您还应该考虑是否真的需要DispatcherTimer ...视图模型在大多数情况下都可以使用常规计时器(例如System.Timers.Timer )来完成。 或者,就您而言,甚至更好-异步方法中的简单Task.Delay

private async Task DefferedUpdate()
{
    await Task.Delay(TimeSpan.FromMilliseconds(20)).ConfigureAwait(false);
    await RefreshAsync().ConfigureAwait(false);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM