我创建了一个非常简单的控制台应用程序,它从 Web 下载大量文件,并将它们放在一个单独的映射文件之后的文件夹结构中。该要求不要求文件需要异步下载。
该程序有效,但问题是如果有人选择使用 ctrl+c 或 ctrl+break 取消应用程序。
如果这样做,正在进行的文件将在程序立即退出时损坏。所以我想在退出之前删除损坏的文件。所以我写了以下处理程序,
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
try
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Program interrupted..deleting corrupted file");
Console.ResetColor();
if (File.Exists(fileInProgress))
{
File.Delete(fileInProgress);
}
}
catch
{
Console.WriteLine("Error occured.");
}
}
fileinprogress
是从调用下载文件的函数更新的全局变量。
上面代码的问题是,如果按 ctrl+c,它会执行代码,但它永远不会将文件作为正在使用的文件删除。所以我跟着https://stackoverflow.com/a/937558/714518并试图等到程序释放文件
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
try
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Program interrupted..deleting corrupted file");
Console.ResetColor();
if (File.Exists(fileInProgress))
{
while (IsFileLocked(fileInProgress))
{
System.Threading.Thread.Sleep(1000);
}
File.Delete(fileInProgress);
}
}
catch
{
Console.WriteLine("Error occured.");
}
}
现在我不明白这种行为。现在,如果按下 ctrl+c,程序会等待几秒钟,然后在不删除文件的情况下继续下载下一个文件。请帮助摆脱这个问题。
实际的应用程序相当大,我只是重新创建了这种情况。有关完整代码,请参阅http://pastebin.com/TRBEAvwi。