简体   繁体   English

当我尝试删除正在使用的文件时,C#程序冻结

[英]C# program freezes when I try to delete file which is being used

researched many topics about this exception, no luck. 研究了许多有关此异常的主题,没有运气。 my simple code: 我的简单代码:

            string t = Path.GetTempFileName();
            t = t.Remove(t.Length - 11, 11);
            var q = Directory.EnumerateFiles(t, "tmp????.tmp");

            var f = q.ToList();
            for (int i = 0; i < q.Count(); i++)
            {
                //      if (Helper.CanReadFile(f[i]))
                try
                {
                    File.Delete(f[i]);
                }
                catch (IOException)
                {

                    break;
                }

            }

I ran this code in Closing event of mainwindow. 我在mainwindow的Closing事件中运行了这段代码。 So it deletes several files, gets into exception, then to "break" statement, and then.. somewhere. 因此,它删除了几个文件,进入了异常,然后执行“ break”语句,然后在某个地方。 Just freezes and pausing debugger leads to nothing. 只是冻结,暂停调试器不会导致任何结果。 I tried several pieces of code to find whether the file is used before deletion, but it gets an exception inside this code (like Helper.CanReadFile) and halts program flow there. 我尝试了几段代码来查找是否在删除文件之前使用了该文件,但是在此代码内它会得到一个异常(例如Helper.CanReadFile),并在那里停止程序流。 I dont really have to delete all files, but I need to stop that freezing. 我真的不必删除所有文件,但我需要停止冻结。 How can I work with this exception so that wont freeze my program? 如何处理此异常,以免冻结程序?

some edit with breakpoints and info for most of them. 一些带有断点和大多数信息的编辑。

1) got an exception http://imgur.com/a/k6of3 1)出现异常http://imgur.com/a/k6of3

2) first step from it, nothing much http://imgur.com/a/FvWjz 2)从它开始的第一步,没什么http://imgur.com/a/FvWjz

3) went back to dispose http://imgur.com/a/LMdiA 3)返回配置http://imgur.com/a/LMdiA

4) went back to event method http://imgur.com/a/FlIUf 4)返回事件方法http://imgur.com/a/FlIUf

5) which was called from onclose http://imgur.com/a/YQUrZ 5)从onclose http://imgur.com/a/YQUrZ调用

6) after that it loops here for a while (I use global hotkey) http://imgur.com/a/0qjdf it goes off after ~10 loops with msg = 130. and my program closes fine if I remove file deletion part. 6)之后,它在这里循环一会(我使用全局热键) http://imgur.com/a/0qjdf它在〜10次循环后以msg = 130熄灭。如果我删除文件删除部分,我的程序会关闭。

7) Freezed part (no code is running message) http://imgur.com/a/WeEGj 7)冻结的部分(没有代码正在运行消息) http://imgur.com/a/WeEGj

When deleting files you can try this: 删除文件时,您可以尝试以下操作:

To run this code on a background Thread you can do several things: 要在后台线程上运行此代码,您可以执行以下几项操作:

Change to private async Task DeleteAllTempFiles() and call it without await ! 更改为private async Task DeleteAllTempFiles() ,然后无需等待就可以调用它!

OR 要么

new Thread(() => { DeleteAllTempFiles(); }).Start();

private void DeleteAllTempFiles()
{
   try
   {
       //Get the temp Path
       DirectoryInfo tempDir = new DirectoryInfo(Path.GetTempPath());
       //Get all matching files
       List<FileInfo> tempFiles = tempDir.GetFiles("tmp????.tmp", SearchOption.AllDirectories).ToList();

       //Collect all files that fail to delete
       List<FileInfo> cannotDelete = new List<FileInfo>();

       //Delete Files:
       DeleteFiles(tempFiles, out cannotDelete);

       //Show what failed (and retry or whatever)
       string message = "Cannot delete the following file(s):";
       cannotDelete.ForEach(file => message += "{file.FullName}{Environment.NewLine}");
       MessageBox.Show(message, "Result");
   }
   catch (Exception ex)
   {
       Debug.Fail(ex.Message);
   }
}

private void DeleteFiles(List<FileInfo> filesToDelete, out List<FileInfo> failedToDelete)
{
   foreach(FileInfo file in filesToDelete)
   {   
      try
      {
         file.Delete();
      }
      catch (IOException ioEx)
      {
         failedToDelete?.Add(file); //<-- Check if failedToDelete != null !!!
         //This will always happen.
         //Since its not "hard fail" you should log it but keep goin !
         //MessageBox.Show($"IO-Exception: {ioEx.Message}");
      }
      catch (Exception ex)
      {
         MessageBox.Show($"Exception: {ex.Message}");
      }
   }
}

If you want to work with the files you can't delete you can process them with this: How do I find out which process is locking a file using .NET? 如果要使用无法删除的文件,可以使用以下方法进行处理: 如何找到使用.NET锁定文件的进程?

For a fast check what locks your files you can use: OpenedFilesView or Windows Sysinternals Process Explorer 要快速检查哪些文件可以锁定,可以使用: OpenedFilesViewWindows Sysinternals Process Explorer

Maybe you can try to set some attributes... Maybe you can get access with this: 也许您可以尝试设置一些属性...也许可以使用以下方法进行访问:

在此处输入图片说明

Sorry for the bad size of the image .. 对不起,图片大小不正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM