WPF DispatcherTimer does not fire
本文关键字:fire not does DispatcherTimer WPF | 更新日期: 2023-09-27 17:58:34
我有一个带有RefreshAsync方法的类,它可能需要很长时间才能执行。我使用Mvvm轻型框架。我需要在对象创建后调用它,但不是每次从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);
}