0

I have single resource (StorageFolder) and which I access in operations:

  • AddFileAsync
  • ReadFileAsync
  • DeleteFolderAsync

I use SemaphoreSlim.WaitAsync class to lock the resource, so it won't be accessed by multiple operations at the same time.

What .net class should I use instead of SemaphoreSlim so that I will be able to call multiple AddFileAsync. and ReadFileAsync concurently, but I won't be able to call AddFileAsync(resp ReadFolderAsync) and DeleteFolderAsync concurently.

In other words, I want to prevent deleting folder while other thread is reading/wrinting to it.

current code (try/finally blocks ommited):

_sempaphore = new SemaphoreSlim(1);

async Task AddFileAsync(){
   await _sempaphore.WaitAsync();
   await _storageFolder.CreateFileAsync(....)
   _sempaphore.Release();
}

async Task DeleteFolderAsync(){
   await _sempaphore.WaitAsync();
   await _storageFolder.DeleteAsync()
   _sempaphore.Release();
}
Liero
  • 25,216
  • 29
  • 151
  • 297
  • Why not depend on the built-in OS filesystem locks? – Stephen Cleary May 11 '17 at 20:28
  • Filesystem locks would throw exception, wouldn't they? – Liero May 12 '17 at 20:52
  • Yes, they would throw. – Stephen Cleary May 13 '17 at 01:13
  • Well, that's what I'm trying to avoid – Liero May 15 '17 at 08:07
  • First, I'd say a single exclusive lock on the entire filesystem would be best. Most drives are spinning platters, so the hardware can only do one thing at a time anyway. If that won't work for you, then a hierarchy of exclusive locks would be my next choice. But if you truly have heavily nested code *with lots of read concurrency*, then you can use nested asynchronous reader/writer locks. Those are some nasty lock hierarchies, though. It just seems like this is a solution for something that isn't a problem. – Stephen Cleary May 15 '17 at 13:25

1 Answers1

1

https://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx

ReaderWriterLockSlim allows multiple readers and one writer.

Edit: now that I read the question more carefully I noticed the async; you can't use ReaderWriterLockSlim if you use async. See ReaderWriterLockSlim and async\await for an alternative.

Community
  • 1
  • 1
Alex Paven
  • 5,539
  • 2
  • 21
  • 35