new APIs for windows phone 8.1

时光毁灭记忆、已成空白 提交于 2019-12-20 12:29:29

问题


I am trying to use these two methods (of WP 8) in windows phone 8.1, but it gives error and doesn't compile, most probably becasue they are removed. I tried searching the new APIs but couldn't get any. What are other alternatives for these.

Dispatcher.BeginInvoke( () => {}); msdn link

System.Threading.Thread.Sleep(); msdn link


回答1:


They still exists for Windows Phone 8.1 SIlverlight Apps, but not for Windows Phone Store Apps. The replacements for Windows Store Apps is:

Sleep (see Thread.Sleep replacement in .NET for Windows Store):

await System.Threading.Tasks.Task.Delay(TimeSpan.FromSeconds(30));

Dispatcher (see How the Deployment.Current.Dispatcher.BeginInvoke work in windows store app?):

CoreDispatcher dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { });



回答2:


Dispatcher.BeginInvoke( () => {}); is replaced by

await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () => {});

and System.Threading.Thread.Sleep(); is replaced by

await Task.Delay(TimeSpan.FromSeconds(doubleValue));



回答3:


Be aware that not only has the API changed (adopting the API from WindowsStore apps), but the way that the Dispatcher was obtained in windowsPhone 8.0 has changed as well.

@Johan Faulk's suggestion, although will work, may return null under a multitude of conditions.

Old code to grab the dispatcher:

var dispatcher = Deployment.Current.Dispatcher;
or
Deployment.Current.Dispatcher.BeginInvoke(()=>{
     // any code to modify UI or UI bound elements goes here 
});

New in Windows 8.1 Deployment is not an available object or namespace.

In order to make sure the Main UI Thread dispatcher is obtained, use the following:

var dispatcher = CoreApplication.MainView.CoreWindow.Dispatcher;
or 
CoreApplication.MainWindow.CoreWindow.Dispatcher.RunAsync(
  CoreDispatcherPriority.Normal,
  ()=>{
      // UI code goes here
});

Additionally, although the method SAYS it will be executed Async the keyword await can not be used in the method invoked by RunAsync. (in the above example the method is anonymous).

In order to execute an awaitable method inside anonymous method above, decorate the anonymous method inside RunAsync() with the async keyword.

CoreApplication.MainWindow.CoreWindow.Dispatcher.RunAsync(
CoreDispatcherPriority.Normal,
**async**()=>{
      // UI code goes here
      var response = **await** LongRunningMethodAsync();
});



回答4:


For Dispatcher, try this. MSDN

private async Task MyMethod()
{
    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { });
}

For Thread.Sleep() try await Task.Delay(1000). MSDN



来源:https://stackoverflow.com/questions/23607096/new-apis-for-windows-phone-8-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!