暂停状态处理
当移动到 Suspened
状态时,会有与此事件相关的特殊处理程序:打开“App.xaml.cx”类并查看 App
构造函数 - 有事件处理程序:
public App()
{
this.InitializeComponent();
//Handle suspending operation with event handler:
this.Suspending += OnSuspending;
}
现在你可以处理暂停事件:
private Dictionary<string, object> _store = new Dictionary<string, object>();
private readonly string _saveFileName = "store.xml";
private async void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
_store.Add("timestamp", DateTime.Now);
await SaveStateAsync();
//TODO: Save application state and stop any background activity
//Here you can use await SuspensionManager.SaveAsync();
//To read more about saving state please refer to below MSDN Blog article:
//https://blogs.windows.com/buildingapps/2016/04/28/the-lifecycle-of-a-uwp-app/#RqKAKkevsAPIvBUT.97
deferral.Complete();
}
private async Task SaveStateAsync()
{
var ms = new MemoryStream();
var serializer = new DataContractSerializer(typeof(Dictionary<string, object>));
serializer.WriteObject(ms, _store);
var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(_saveFileName, CreationCollisionOption.ReplaceExisting);
using (var fs = await file.OpenStreamForWriteAsync())
{
//because we have written to the stream, set the position back to start
ms.Seek(0, SeekOrigin.Begin);
await ms.CopyToAsync(fs);
await fs.FlushAsync();
}
}