I had a similar problem, so I hope that my solution is going to help you too.
Basically, the problem is that ReaderWriterLockSlim has thread affinity, meaning that thread that acquired a lock is the only one that can release it.
Solution to this is to create one more dedicated thread, but opposed to what you suggested, this thread is going to be dedicated to acquiring and releasing a lock.
I guess that your code looks something like this:
public class ClassUsingReaderWriterLockSlim
{
private ReaderWriterLockSlim rwsLock;
public void MethodThatAcquiresLock()
{
rwsLock.EnterWriteLock();
}
public void MethodThatReleasesLock()
{
rwsLock.ExitWriteLock();
}
}
And a code that solves your problem will look like this:
public class ClassUsingReaderWriterLockSlim
{
private ReaderWriterLockSlim rwsLock;
Thread dedicatedThreadForReaderWriterLockSlim;
Queue<string> commandsForDedicatedThread;
public ClassUsingReaderWriterLockSlim()
{
commandsForDedicatedThread = new Queue<string>();
dedicatedThreadForReaderWriterLockSlim = new Thread(ThreadFunction);
dedicatedThreadForReaderWriterLockSlim.Start();
}
private void ThreadFunction(object obj)
{
while (!terminatingCondition)
{
// Wait until something is in queue...
if (commandsForDedicatedThread.Count > 0)
{
switch (commandsForDedicatedThread.Dequeue())
{
case "ENTER LOCK":
rwsLock.EnterWriteLock();
case "EXIT LOCK":
rwsLock.EnterWriteLock();
default:
// Do nothing...
}
}
}
}
public void MethodThatAcquiresLock()
{
commandsForDedicatedThread.Enqueue("ENTER LOCK");
}
public void MethodThatReleasesLock()
{
commandsForDedicatedThread.Enqueue("EXIT LOCK");
}
}
Well, for you production code you would make this a little differently but the basic idea is to have dedicated thread that is going to do locking and unlocking, and in this way it won't be important from which thread call comes to the methods that are supposed to lock and unlock code/resources...
Hope this helps you.