为什么我不能在我的应用程序暂停时删除文件?
本文关键字:删除 文件 程序暂停 应用 不能 我的 为什么 | 更新日期: 2023-09-27 17:53:48
我已经隔离了下面的代码,它在OnNavigatedTo事件中工作,所以我知道代码是有效的。但是,我不能在那里使用它。我需要在suspend事件中使用它。但在那里行不通。当我设置断点时,它们不会在这个事件中被击中。没有编译时或运行时错误。
怎么回事?
async void App_Suspending(
Object sender,
Windows.ApplicationModel.SuspendingEventArgs e)
{
IReadOnlyList<StorageFile> thefiles;
var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
Windows.Globalization.DateTimeFormatting.DateTimeFormatter formatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longtime");
thefiles = await localFolder.GetFilesAsync();
foreach (var f in thefiles)
{
await f.DeleteAsync(StorageDeleteOption.Default);
}
}
我的猜测是,当你在这个方法中等待时,应用程序退出了suspend方法,并以这种方式给予操作系统杀死进程的权限。您可以通过在第一个await语句之后(在foreach语句中)放置一个断点并检查是否到达该断点来测试这一点。
我找到了解决办法。它包括检查应用程序是否被用户关闭。如果是这样,(在我的情况下)删除这些临时文件是可以的。你可以在App.xaml.cs文件中的onlaunching方法中这样做:
if (args.PreviousExecutionState == ApplicationExecutionState.ClosedByUser)
{
IReadOnlyList<StorageFile> thefiles;
var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
Windows.Globalization.DateTimeFormatting.DateTimeFormatter formatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longtime");
thefiles = await localFolder.GetFilesAsync();
foreach (var f in thefiles)
{
await f.DeleteAsync(StorageDeleteOption.Default);
}
}