使用Async Task with Dispatcher从ViewModel中为WP8.1 WinRT循环更新UI线程

时间:2014-09-17 12:11:39

标签: c# multithreading windows-runtime async-await windows-phone-8.1

我是Windows Phone Dev的新手,我正在将我的WP8 SilverLight应用程序迁移到WP8.1 WinRT。下面是我的ViewModel for WP8上的工作代码,该代码不适用于Store应用程序。

代码背后的逻辑是每秒更新UI线程上的Xaml txtBox值,这是在UpdateTicker()方法内完成的。

WP8工作代码:

        Task.Run(async () =>
        {
            while (true)
            {
                await Task.Delay(1000);
                Deployment.Current.Dispatcher.BeginInvoke(new Action(() =>
                {
                    UpdateTicker(); // this method gets called every second
                }), null);
            }
        });

经过大量的搜索,MSDN和SO,这就是我所需要的,下面的代码编译好wp8.1 winRT但是仍然不起作用 - 当放置一个断点时,调试器到达UpdateTicker()只执行一次,而UpdateTicker方法应该每秒调用一次(这是第一个代码块发生的事情)

WP8.1 WinRT代码:

        Task.Run(async delegate
        {
            while (true)
            {
                await Task.Delay(1000);
                CoreDispatcher dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
                await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    UpdateTicker();  // this method does not get called every second
                });
            }
        });

对于从ViewModel为wp8.1 env一起使用Async Task和Dispatcher.BeginInvoke(或同样)的任何指导表示赞赏。

1 个答案:

答案 0 :(得分:9)

实际上,我建议您避免 DispatcherCoreDispatcher等。总有更好的解决方案。

在这种情况下,您可以使用进度更新。以下是适用于Windows Phone Silverlight 8以及Windows Phone Apps 8.1的一些代码:

IProgress<object> progress = new Progress<object>(_ => UpdateTicker());
Task.Run(async () =>
{
  while (true)
  {
    await Task.Delay(1000);
    progress.Report(null);
  }
});

附注:在生产代码中,您几乎不想只启动Task.Run而不对返回的Task执行任何操作。至少,你应该有一些代码(异步)等待从循环中捕获任何异常。