C# program freezes when I try to delete file which is being used
<p>researched many topics about this exception, no luck. my simple code:</p>

<pre><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 &lt; q.Count(); i++)
            {
                //      if (Helper.CanReadFile(f[i]))
                try
                {
                    File.Delete(f[i]);
                }
                catch (IOException)
                {

                    break;
                }

            }
</code></pre>

<p>I ran this code in Closing event of mainwindow.
So it deletes several files, gets into exception, then to "break" statement, and then.. somewhere. 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. <strong>I dont really have to delete all files, but I need to stop that freezing.</strong> How can I work with this exception so that wont freeze my program?</p>

<p>some edit with breakpoints and info for most of them.</p>

<p>1) got an exception <a href="https://imgur.com/a/k6of3" rel="nofollow noreferrer">http://imgur.com/a/k6of3</a></p>

<p>2) first step from it, nothing much <a href="https://imgur.com/a/FvWjz" rel="nofollow noreferrer">http://imgur.com/a/FvWjz</a></p>

<p>3) went back to dispose <a href="https://imgur.com/a/LMdiA" rel="nofollow noreferrer">http://imgur.com/a/LMdiA</a></p>

<p>4) went back to event method <a href="https://imgur.com/a/FlIUf" rel="nofollow noreferrer">http://imgur.com/a/FlIUf</a></p>

<p>5) which was called from onclose <a href="https://imgur.com/a/YQUrZ" rel="nofollow noreferrer">http://imgur.com/a/YQUrZ</a></p>

<p>6) after that it loops here for a while (I use global hotkey) <a href="https://imgur.com/a/0qjdf" rel="nofollow noreferrer">http://imgur.com/a/0qjdf</a>   it goes off after ~10 loops with msg = 130. and my program closes fine if I remove file deletion part.</p>

<p>7) Freezed part (no code is running message) <a href="https://imgur.com/a/WeEGj" rel="nofollow noreferrer">http://imgur.com/a/WeEGj</a></p>