我创建了一个非常简单的控制台应用程序,该应用程序从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。
听起来您需要一种信号来指示您的下载代码停止下载。通过查看此示例,我认为最好的位置可能是在Console_CancelKeyPress函数的输入位置。否则,您的下载代码将永远不会意识到它需要释放文件锁并停止下载。
例如:
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
try
{
Interlocked.Increment(ref globalStopFlag);
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.");
}
}
void SomeDownloadFunction()
{
using (somefile)
{
while (!downloadFinished)
{
long doINeedToStop = Interlocked.Read(ref globalStopFlag)
if (doINeedToStop != 0)
return;
//Download the next set of packets and write them to somefile
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句