Hi. I've a multithreaded service application with many threads accessing a common resource. I have a typical Readers/Writers environment, where many threads may read at the same time but only one can write to the resource, exclusively.
The thing is, whenever two threads (or more) asks for writing permission, I do not need to wait for the first thread to finish, I can just abort it (the first thread is no longer needed) and execute the second thread. Since writing is an expensive operation, it's desirable that I abort the first thread and execute the second.
So, here's my doubt: if I abort a thread that holds a lock, will it release the lock?
My simplified code looks like this:
private static System.Threading.Thread WritingThread =
System.Threading.Thread(MyClass.PerformWriting)
private void TryWrite()
{
If (WritingThread.IsAlive)
WritingThread.Abort();
WritingThread.Start();
}
private void PerformWriting()
{
MyReaderWriterLockSlim.EnterWriteLock();
try{
}
finally{
MyReaderWriterLockSlim.ExitWriteLock();
}
}
So here's the deal. I have a commom fixed writing thread for everybody, so I can test if the thread is already running, and if is, I can just abort it and initiate it again. This get the effect of aborting the first writing and executing the second. Whenever a thread needs to write to the resouce, it just calls the TryWrite function. The original calling thread doesn't need to wait the end of the operation, so it returns and finishes.
But, since "writing operation" takes a long time, it is more likely that the WritingThread will be aborted when it is writing, that is, when it holds the lock.
Is that code ok, or it will deadlock when the thread gets aborted in the middle of the writing?