我在长时间运行的 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
}
}
}
}
最佳答案
我有一个类似的问题,单独调用 GC.Collect()
并不总是有帮助,因为它在后台线程中启动垃圾收集,所以它会立即返回。
试着打电话
GC.WaitForPendingFinalizers();
在 GC.Collect()
之后。
关于c# - 取消任务时删除另一个进程持有的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25692662/