0

I am using the following code in C# Windows Service to create or overwrite an existing file.

function DonwnloadFile(string destinationfolder, string filename)
{
    using (var outputFileStream = System.IO.File.Create(
        destinationfolder + "\\" + filename, BUFFER_SIZE))
    {
        //Downloads a large file from cloud and writes it to the outputFileStream
        //...
        //...
    }
}

While the file (which is very large in size) is getting downloaded, another request to DownloadFile method is made since the source file got updated. However, an exception is thrown:

The process cannot access the file '[FileName with Path]' because it is being used by another process.

How do I implement a solution so that subsequent requests to overwrite the same file wait till the previous file write operation for the same file finishes. Also, the solution should allow requests to a overwrite a different file should not wait as it won't throw any exception.

Can I use lock while ensuring lock only works based on the filename. Or can someone please suggest a better solution for the problem.

Note: DonwloadFile method would be called by a different thread each time.

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
Gags
  • 827
  • 2
  • 13
  • 29
  • Yeah you're going to need a lock to do this, there is no built-in functionality in Windows to wait on file access. Maybe a `ConcurrentDictionary` – Charlieface Feb 21 '21 at 13:23
  • Note that, while using a synchronization primitive is cleaner, you can just use the file itself for synchronization. Wrap the file access with a try/catch, and reimplement a retry logic after a few seconds when it fails – Kevin Gosse Feb 21 '21 at 13:54
  • You might find this interesting: [Asynchronous locking based on a key](https://stackoverflow.com/questions/31138179/asynchronous-locking-based-on-a-key). Also [this](https://stackoverflow.com/questions/57022754/send-parallel-requests-but-only-one-per-host-with-httpclient-and-polly-to-gracef/ "Send parallel requests but only one per host with HttpClient and Polly to gracefully handle 429 responses") one, in case you are interested for a TPL Dataflow approach. – Theodor Zoulias Feb 21 '21 at 14:45
  • Do you download the file from the Internet or do you want to copy the file? – Meysam Asadi Feb 21 '21 at 17:20
  • Can you not make the download cancel-able if the source file gets changed? Also, you will need the lock AND a retry-with-wait mechanism, since the OS ultimately "owns" the file I/O. – Chris O Feb 21 '21 at 21:10

0 Answers0