Reputation:
I'm trying to properly handle files in a web app. When downloading a file I lock on an object:
lock(lockObject)
{
//Download file here.
}
so that if that same file is about to be deleted from another thread while in the middle of the download, the "delete" thread waits for the "download" thread to finish first:
lock(lockObject)
{
//Delete file here.
}
This works, but presents another problem: two threads cannot download the file simultaneously.
How can I make it so that multiple threads can run the "download" code simultaneously but at the same time not allow any thread to run the "delete" code until the "download" threads are done?
I know the answer is somewhere in the Monitor
class, but I'm not sure how to pull it off.
Upvotes: 0
Views: 62
Reputation: 133995
Possibly a ReaderWriterLockSlim would do what you need. Basically, you treat the download threads as readers and the delete threads as writers. You can have any number of readers, but any writer requires exclusive access. So if any file is being downloaded when the delete method calls EnterWriteLock
, the delete thread will have to wait until all current downloads have finished.
ReaderWriterLockSlim theLock = new ReaderWriterLockSlim();
void Delete(filename)
{
theLock.EnterWriteLock();
try
{
// do delete stuff here
}
finally
{
theLock.ExitWriteLock();
}
}
void Download(filename)
{
theLock.EnterReadLock();
try
{
// do delete stuff here
}
finally
{
theLock.ExitReadLock();
}
}
Upvotes: 0