First of all, I already saw this question , and I (sort of) understand why I get this exception, I would like to know that this is the best way to fix it. My code looks something like this (this is a WinRT application):
public App()
{
this.InitializeComponent();
this.Suspending += this.OnSuspending;
_model = new Model();
_model.LoadData();
}
public async void LoadData()
{
StorageFolder folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
StorageFile file = await folder.GetFileAsync(@"Assets\Data.json");
string data = await FileIO.ReadTextAsync(file);
var dataList = JsonConvert.DeserializeObject<List<MyDataClass>>(data);
var dispatcher = CoreApplication.MainView.CoreWindow.Dispatcher;
foreach (var item in dataList)
{
await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
() => {
});
}
}
Obviously, the method is LoadData
async void
not the best solution. However, as you can see, I have to make some calls to asynchronous functions (to read data from a file) inside it. Now I can think of two possible solutions:
- Change
LoadData
to public async Task LoadData()
and change its call in the application designer to _model.LoadData().GetAwaiter().GetResult();
to start it synchronously; LoadData
public void LoadData()
await
, awaiter, . StorageFile file = folder.GetFileAsync(@"Assets\Data.json").GetAwaiter().GetResult()
.
, , ? , "A " ?