I'm trying to save app data when the app is closing/deactivating. In WP8 I used StorageFile, which only supports Async methods.
The problem is (as I suspected and confirmed when reading this article), simply stated, that the OS lifecycle events and async methods don't mix well together. So, this does not work (even without async/await)
private async void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
var dataSvc = SimpleIoc.Default.GetInstance<ICachedDataService>();
await dataSvc.StoreCachedDataAsync();
}
The article suggests 2 workaround, neither one seems ideal:
- Use a different API, e.g. IsolatedStorage instead of StorageFolder/File, which supports synchronous operations.
- Save-as-you-go vs. save in the end
My problem with (2) is that it still doesn't guarantee that it would have time to save even if I initiate it as soon as possible.
My problem with (1) is... beh... I'm using a ServiceLocator/IoC pattern (I could never remember which pattern is what), so this forces me to introduce synchronous operations in the interface of ICachedDataProvider
, for example.
Is there any other approach? Is it possible to convert an Async method into a synchronous method to increase code reuse?