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

Nis*_*hil 2 c# multithreading async-await windows-runtime 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);
            }
        });
Run Code Online (Sandbox Code Playgroud)

经过大量的搜索,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
                });
            }
        });
Run Code Online (Sandbox Code Playgroud)

有关在ViewModel中为wp8.1 env一起使用Async Task和Dispatcher.BeginInvoke(或同样)的任何指导都表示赞赏.

Ste*_*ary 9

其实,我建议你避开 Dispatcher,CoreDispatcher等总有更好的解决方案.

在这种情况下,您可以使用进度更新.以下是适用于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);
  }
});
Run Code Online (Sandbox Code Playgroud)

旁注:在生产代码中,您几乎从不想只是启动一个Task.Run而不对返回做任何事情Task.至少,你应该有一些代码(异步)等待从循环中捕获任何异常.