【发布时间】:2016-09-23 18:27:16
【问题描述】:
我正在尝试在 ViewDidLoad 上初始化视图模型。我需要在 ViewModel 初始化代码中调用一些异步方法,所以我将异步代码从构造函数中移到了async factory method 中。
我在 UIViewController 子类中将 ViewDidLoad 和 ViewWillAppear 标记为 async void,但由于某种原因,在第 4 行执行时,ViewWillAppear 被启动,第 11 行抛出 NullReferenceException,因为ViewModel 尚未初始化。
我怀疑 Xamarin 不能等待 ViewDidLoad 完成,因为它是 async void,但我必须在这里使用 async void,因为它覆盖了一个方法。
MyCustomUiViewController.cs
1 public override async void ViewDidLoad()
2 {
3 base.ViewDidLoad();
4 ViewModel = await ViewModel.CreateAsync();
5 OtherStuff();
6 }
7
8 public override async void ViewWillAppear(bool animated)
9 {
10 base.ViewWillAppear(animated);
11 ViewModel.SomeMethod(); // <-- NullReferenceException
12 AttachViewModelToViewBindings();
13 }
如果有更好的模式来实例化异步 ViewModel,我愿意更改架构。
【问题讨论】:
-
您将函数标记为异步,但这并不意味着它们会被等待。不确定是不是这样,但也许?
-
我也遇到了同样的问题,请问您找到解决方法了吗?
-
@ZeaShah 我在下面添加了一个可能有帮助的答案
标签: c# .net xamarin xamarin.ios async-await