取消任务时删除其他进程持有的文件

时间:2014-09-05 19:24:11

标签: c# task-parallel-library cancellation

我在长时间运行Task内创建文件(Sqlite数据库)时遇到问题如果任务被取消,我无法正确删除它。它抛出IOException关于在另一个进程中使用,我假设另一个进程是Task

如果我没有取消任务并让它完成,它会正确删除。

 var cancellationTokenSource = new CancellationTokenSource();
 var cancellationToken = cancellationTokenSource.Token;

 string dbFilePath = @"C:\test.db";

 Task.Factory.StartNew(() => 
     {
          PopulateDatabase(dbFilePath);
     }, cancellationToken).ContinueWith((result) =>
     {
          GC.Collect();
          File.Delete(dbFilePath);   // <--- Used in other process exception occurs here
     }, TaskScheduler.FromCurrentSynchronizationContext()  // Called from a GUI thread
 );

 cancellationTokenSource.Cancel(); // This occurs after the task is running

 // I use using blocks in here, so the proper dispose methods should be called.
 private void PopulateDatabase(string filePath) {
     using(var conn = new SQLiteConnection(@"Data Source="+filePath+";")) {
         // Do a bunch of work
     }
 }

我甚至尝试修改PopulateDatabase以接纳CancellationToken并正常退出,但同样的错误也会发生。

 private void PopulateDatabase(string filePath, CancellationToken cancelToken) {
     using(var conn = new SQLiteConnection(@"Data Source="+filePath+";")) {
         // Do a bunch of work
         while(true) {
             if (cancelToken.IsCancellationRequested)
             {
                  return; // I assume this calls the appropriate Dispose methods
             }
         }
     }
 }

1 个答案:

答案 0 :(得分:-1)

我遇到了类似的问题并且单独调用GC.Collect()并不总是有帮助,因为它在后台线程中启动垃圾收集,因此它会立即返回。

尝试拨打

GC.WaitForPendingFinalizers();

GC.Collect()之后。