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).


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.


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