我有一个带有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);
}发布于 2016-07-25 02:15:10
必须从具有活动Dispatcher的线程或通过将活动调度程序传递给计时器的构造函数来创建DispatcherTimer。
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);
}https://stackoverflow.com/questions/38554691
复制相似问题