尽管使用 Polly,但删除文件在使用时会引发异常
我正在尝试创建某种 C# 应用程序原型。我的目标是在文件可用时将其删除,这样就不会被另一个进程锁定。很多时候我需要读取/删除/移动仍在使用的文件,因为它们是由网络上的另一个应用程序写入的。网络延迟导致文件使用异常。
在我的演示中,我创建了另一个控制台应用程序,每 5 秒写入一次。一行到同一个文件,同时它保持文件打开,所以这将起作用。
因此,我想将删除/移动操作包装在 Polly 策略中,但是当我尝试时,仍然有 IOException
: 文件正在被另一个进程使用。我以为这是 Polly 捕获的,但显然我错了......
这段代码有什么问题?
当我查看 InnerException
时,它是 null
吗?
static void Main(string[] args)
{
var MAX_RETRIES = 5;
Console.WriteLine($"Attempting to delete the file {fileName}\r\nPress any key to continue....");
Console.ReadKey();
//Build the policy
var retryPolicy = Policy
.Handle<IOException>()
.Or<Exception>()
.Retry(MAX_RETRIES);
//Execute the error prone code with the policy
retryPolicy.Execute(() =>
{
Console.WriteLine($"Starting File-deleting on {fileName}");
if (File.Exists(fileName))
File.Delete(fileName); // <== here's where the exception occurs !
Console.WriteLine("File deleted");
});
Console.WriteLine("Press any key to quit");
var s = Console.ReadLine();
if (s == "quit");
Environment.Exit(0);
}
I'm trying to create some sort of prototype of a C# application. My goal is to delete a file when it becomes available, so not locked by another process. Lots of times I need to read/delete/move files which are still in use cause they are being written by another application on the network. Network-delay causes the file-in-use exception.
For my demo I created another console application which writes every 5 sec. a line to the same file and in the mean time it keeps the file open, so this will work.
So I want to wrap the delete/move action in a Polly policy, but when I'll try there is still the IOException
: file in use by another process. I assumed this was captured by Polly, but apparently I'm wrong...
What's wrong in this code ?
When I take a look at the InnerException
, it's null
?
static void Main(string[] args)
{
var MAX_RETRIES = 5;
Console.WriteLine(quot;Attempting to delete the file {fileName}\r\nPress any key to continue....");
Console.ReadKey();
//Build the policy
var retryPolicy = Policy
.Handle<IOException>()
.Or<Exception>()
.Retry(MAX_RETRIES);
//Execute the error prone code with the policy
retryPolicy.Execute(() =>
{
Console.WriteLine(quot;Starting File-deleting on {fileName}");
if (File.Exists(fileName))
File.Delete(fileName); // <== here's where the exception occurs !
Console.WriteLine("File deleted");
});
Console.WriteLine("Press any key to quit");
var s = Console.ReadLine();
if (s == "quit");
Environment.Exit(0);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这有点超出了我的专业知识,因为我从未使用过 Polly,但可以尝试的一件事是在
if(file.Exists(filename))
内部抛出一个 try catch。仅提出这一点,因为它看起来不像您在检查它是否存在后检查它是否正在使用。This is a little above my expertise as I have never used Polly, but one thing to try would be to throw a try catch inside of the
if(file.Exists(filename))
. Only bringing this up as it doesn't look like you are ever checking if it is in use after checking if it exists.