我有一个 wpf xbap 应用程序,可以在后台下载一些数据。需要在应用程序退出时停止下载并刷新缓存。现在实现如下:
App.xaml :
<Application Exit="ApplicationExit">
应用程序.xaml.cs:
private void ApplicationExit(object sender, ExitEventArgs e)
{
BackgroundImageLoader.Instance.Stop(); // target
ViewModelLocator.Cleanup();
FileCacheHelpers.FlushTemporaryFolder();
}
背景图像加载器.cs:
// Thread-safe singleton
public sealed class BackgroundImageLoader
{
private static volatile BackgroundImageLoader _instance;
private static readonly object SyncRoot = new object();
private BackgroundImageLoader() { }
public static BackgroundImageLoader Instance
{
get
{
if (_instance == null)
{
lock (SyncRoot)
{
if (_instance == null)
_instance = new BackgroundImageLoader();
}
}
return _instance;
}
}
// other properties, omitted for conciseness
private Task loaderTask;
private CancellationTokenSource ts;
public void Start()
{
ts = new CancellationTokenSource();
var ct = ts.Token;
loaderTask = Task.Factory.StartNew(() =>
{
// TaskList is an array of tasks that cannot be canceled
// if they were executed, so i want to actually cancel the
// whole pool after last non-canceled operation was ended
foreach (var task in TasksList)
{
if (ct.IsCancellationRequested)
{
Debug.WriteLine("[BackgroundImageLoader] Cancel requested");
// wait for last operation to finish
Thread.Sleep(3000);
FileCacheHelpers.FlushTemporaryFolder();
break;
}
task.DoSomeHeavyWorkHere();
}
}, ct);
}
public void Stop()
{
if (loaderTask != null)
{
if (loaderTask.Status == TaskStatus.Running)
{
ts.Cancel();
}
}
}
}
Stop 被调用,loaderTask 不为 null 并且 Status 正在运行,但在 ts.Cancel() IsCancellationRequested 属性未更改之后(即使在将整个任务包装在 while(true){..} 中,如此处所述)。加载停止,但我想这要归功于自动 GC。我的刷新方法没有执行。我错过了什么?ps 另外我需要重构功能以同时在单独的线程中运行任务,但害怕副作用。任何帮助表示赞赏。提前致谢。