StorageFolder.CreateFileAsync crashes when called from App.OnSuspending

倖福魔咒の 提交于 2019-12-01 18:16:39

The problem was the call to the Save-method. Only the first part (creation of the file) was been waited for, the second part (saving XML) was done async, and therefore the deferral of the suspending operation has not been until the end of the save process.

A possible solution to avoid this problem is to wait explicitely for the completion of the save-operation. This can be accomplished by declaring the OnSuspending-method as aysnc and then waiting for the completion of the save Operation with the await keyword (please note the Task return-type of the Save-method).

private async void OnSuspending(object sender, SuspendingEventArgs e){                        
     var deferral = e.SuspendingOperation.GetDeferral();                       
     if (null != m_document) await Save();
     deferral.Complete();
}

async Task Save(){
    var folder = KnownFolders.DocumentsLibrary;       
    var file = await folder.CreateFileAsync(GetFileName(),Windows.Storage.CreationCollisionOption.ReplaceExisting);                

    var xDoc = GetXDocument();
    using (var stream = await file.OpenStreamForWriteAsync()){
       xDoc.Save(stream);                    
    }           
}

I hope this post helps someone else who has been fallen into the same pitfall (I'm wondering why the problem has not occured with the beta of w8, but I think that MS has optimized the application termination-process and therefore there is less time for unexpected work after the suspension-process)...

You're running out of time. You start out with approximately 5 seconds, but if you don't declare that you will use it then your time will be cut short. Try this:

private async void OnSuspending(object sender, SuspendingEventArgs e)
{
    var deferral = e.SuspendingOperation.GetDeferral();
    try
    {
        await Task.Delay(1000);
        Debug.WriteLine("Done");
    }
    finally
    {
        deferral.Complete();
    }
}

See here for more details. See here for the official documentation:

Note If you need to do asynchronous work when your app is being suspended you will need to defer completion of suspend until after your work completes. You can use the GetDeferral method on the SuspendingOperation object (available via the event args) to delay completion of suspend until after you call the Complete method on the returned SuspendingDeferral object.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!