【发布时间】:2021-08-17 08:08:03
【问题描述】:
我有一个场景,我需要将文件从本地磁盘一个一个上传到 azure blob 存储,并在上传后在磁盘上删除它们。问题是,一旦上传了文件,我不想等到该文件被删除后再上传下一个文件。
我可以看到.NET 中没有异步文件删除。那么处理这种情况的最佳方法是什么,我该如何实现呢.. 目前我正在使用以下代码,但它似乎不稳定。
private event EventHandler FileDeleteEvent;
public async Task SendBulkTelemetryMessageConsumer()
{
try
{
this.FileDeleteEvent +=this.FileDeleteEventHandler;
// Logic to upload a file to blob storage
await this.Log.Debug($"Deleting the file {file}");
this.FileDeleteEvent(file);
}
catch()
{
// Exception handling
}
}
private void FileDeleteEventHandler(string filePath)
{
if (!File.Exists(filePath))
{
this.Log.Debug($"The file {filePath} doesn't exist.");
}
else
{
while (this.IsFileLocked(filePath))
{
Thread.Sleep(1000);
}
this.Log.Debug($"Deleting the file from the path {filePath}");
File.Delete(filePath);
}
}
private bool IsFileLocked(string filePath)
{
try
{
using (File.Open(filePath, FileMode.Open))
{
return true;
}
}
catch (IOException e)
{
this.Log.Error("Exception occured while deleting the file, Exception is {e}", e);
}
return false;
}
我应该让事件处理程序异步无效还是异步任务?
或者在我不必使用任何事件和事件处理程序的情况下使用 Fire and Forget 方法是否更合适?
【问题讨论】:
-
谁打电话给
SendBulkTelemetryMessageConsumer?file来自哪里?你能提供一个更完整的例子吗? -
也不要
Thread.Sleep,使用Task.Delay并等待它 -
也许这会有所帮助; stackoverflow.com/questions/10606328/…
-
@asaf92,SendBulkTelemetryMessageConsumer 方法由其他内部方法之一调用,该文件来自从配置文件中读取文件路径。无论如何,我已经在这里注释掉了该逻辑,因为该代码块(获取文件,根据我们的业务逻辑验证它们并上传它们)非常大并且与我提出的问题无关。
-
什么时候删除文件需要这么长时间?就像写分配表一样。
标签: c# events async-await event-handling file-handling