在WPF XBAP应用程序退出期间取消后台任务

时间:2012-10-03 09:03:59

标签: c# wpf task xbap cancellation

我有一个wpf xbap应用程序,可以在后台下载一些数据。在应用程序退出时需要停止下载和刷新缓存。现在实施如下:
App.xaml:

<Application Exit="ApplicationExit">

App.xaml.cs:

private void ApplicationExit(object sender, ExitEventArgs e)
{
    BackgroundImageLoader.Instance.Stop(); // target
    ViewModelLocator.Cleanup();
    FileCacheHelpers.FlushTemporaryFolder();
}

BackgroundImageLoader.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){..}中,如上所述{{3} })。加载停止,但我想这只是由于自动GC。我的flush方法没有执行。我错过了什么? 附:此外,我需要重构功能,以同时在单独的线程中运行任务,但害怕副作用。任何帮助赞赏。提前谢谢。

1 个答案:

答案 0 :(得分:1)

添加了一些我在处理过程中设置和检查的手动标志,并在Start()开头调用Stop(),因此行为是可以接受的。