异步编程是风靡一时的移动应用程序开发的很好的理由。使用异步方法对于长时间运行的任务,比如下载数据,有助于保持您的用户界面响应,而不是使用异步方法,或不当使用 async/await,可以使应用程序的UI停止响应用户输入,直到长时间运行的任务完成为止。这可能导致用户体验不佳,从而导致对应用程序商店的评论不好,这对商业永远都不好。
今天我们将异步使用一看,如何利用它来防止不期望的ListView中的行为和意外。
什么是async/await?
async 和await 关键词介绍了.NET 4.5使调用异步方法容易使你的代码更易读的异步。async/await的是语法糖,采用TPL(任务并行库)的幕后。如果您想在任务完成前在.NET 4.5上启动一个新的任务并在UI线程上运行代码,那么您的代码将类似于此:
// Start a new task (this launches a new thread) Task.Factory.StartNew (() => { // Do some work on a background thread, allowing the UI to remain responsive DoSomething(); // When the background work is done, continue with this code block }).ContinueWith (task => { DoSomethingOnTheUIThread(); // the following forces the code in the ContinueWith block to be run on the // calling thread, often the Main/UI thread. }, TaskScheduler.FromCurrentSynchronizationContext ());
那不是很漂亮。使用async/await,上述代码变理为
await DoSomething(); DoSomethingOnTheUIThread();
上面的代码在第一个示例中与第三方代码一样在后台编译,所以我们注意到,这只是语法糖,它是多么的甜蜜!
使用Async: Pitfalls
阅读有关使用async/await,可能见过“异步的方式“抛四周,但这到底是什么意思呢?简单地说,这意味着任何一个异步方法调用的方法 (一个方法,在其签名async关键字) 应该使用await关键字调用异步方法时。在调用异步方法的没有使用时候 await关键词会得到一个异常结果,抛出一个运行时期的异常,这会导致很难追踪问题。调用asyncUsing the 关键词标记的方法必须使用await关键词,比如:
async Task CallingMethod() { var x = await MyMethodAsync(); }
这带来一个问题,