I have a scenario where i need to upload files from local disk to azure blob storage one by one and delete them on the disk once uploaded. The thing is , once a file is uploaded , I don't want to wait till that file is deleted to go and upload the next file.
I can see that there is no asynchronous file delete in .NET. So what is the best way to handle this scenario and how can i implement the same.. Currently I'm using the following code, but it seems to be unstable.
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;
}
should i make the event handler async void or async task?
or is it more appropriate to use Fire and Forget method where i dont have to use any events and event handlers?