Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't there an asynchronous file delete in .net?

You have the asynchronous versions of read and write (begin/end functions), but not of delete (that I can tell). Is there any reason for this? Isn't there as much reason to do delete asynchronously as read/write?

Using threading to simulate asynchronous behavior is not the same as asynchronous functions. Big difference, sure you get the perceived parallel processing, but it's not really preventing blocking, that other thread is still blocked waiting for the file i/o to complete. The real asynchronous functions (begin/end functions) operate at a system level, they queue up file i/o, let the application proceed, and let the application know when it is ready to proceed with the file i/o (allowing you to do other things while you wait for the file i/o to come available).

like image 844
aepheus Avatar asked May 15 '12 18:05

aepheus


People also ask

What is asynchronous file?

Asynchronous operations enable you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.

Which class contains methods like CopyToAsync ReadAsync WriteAsync?

Stream class contains methods such as CopyToAsync, ReadAsync, and WriteAsync alongside the synchronous methods CopyTo, Read, and Write.


2 Answers

This would be useful. DeleteFile could take up to 30s if deleting on a disconnected network share.

The reason is likely to be that there is no native function to delete a file asynchronously. The managed APIs generally are wrappers around the unmanaged ones.


Now why is there no native asynchronous file delete API? Native async deletion is hard to implement on Windows as it is. DeleteFile does in pseudocode CreateFile plus NtSetInformationFile(Disposition, Delete) plus CloseHandle. There is no async CreateFile (in my opinion a design bug in Windows). NtSetInformationFile just sets a flag on the file data structure in the kernel. It can't be asynchronous. The actual deletion happens when the last handle is closed. I think this might make CloseHandle blocking which is another design issue in Windows. There is no async CloseHandle.

like image 81
usr Avatar answered Sep 20 '22 07:09

usr


How about this:

public static class FileExtensions {    public static Task DeleteAsync(this FileInfo fi) {       return Task.Factory.StartNew(() => fi.Delete() );    } } 

Then you can just do:

FileInfo fi = new FileInfo(fileName); await fi.DeleteAsync(); // C# 5 fi.DeleteAsync().Wait(); // C# 4 
like image 27
Michael Kennedy Avatar answered Sep 19 '22 07:09

Michael Kennedy