我想在ViewModel的构造函数中加载一些数据,但由于WinRT的异步性质,我不得不使用异步方法。不幸的是,我不能有一个异步构造函数,所以我尝试使用异步方法作为同步方法。我确信在加载应用程序时有更好的方法来加载数据(异步),但我现在的想法是空白。构造函数WinRT异步数据加载
我正在寻找一种方法来修复我的应用程序,使用我要下去的思路,或者使用更合适的方法来解决这个问题。
该代码非常简单(甚至缺少ViewModel)只是为了演示我面临的问题。
public sealed partial class MainPage : Page
{
public string Data { get; set; }
public DataService _dataService { get; set; }
public MainPage()
{
this.InitializeComponent();
_dataService = new DataService();
var t = _dataService.GetData();
Data = t.Result;
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
}
}
public class DataService
{
public async Task<string> GetData()
{
//Force async
await Task.Delay(1);
return "Hello";
}
}
亲切的问候
记住错误处理。如果''async'初始化方法返回的'Task'永远不会被观察到,任何异常都会被悄悄吞下。所以一定要在'InitializeAsync'中有一个'try' /'catch'或者另一个方法'await'结果。 –
当然。无论调用是在初始化程序还是其他任何可能导致错误状态的方法中,这都适用。 –