Reputation: 11361
Hello i need to use writerreaderlock in my method. I want to know how use it correctly.
I got a dictionary of ObjectA
public class ObjectA
{
public ReaderWriterLock RWL {get;set;}
public ObjectB obj {get;set;}
public ObjectA()
{
RWL = new ReaderWriterLock();
}
}
public class ObjectB
{
int TTL {get;set;}
string Value {get;set;}
}
In my method I use a dictionary of ObjectA, the key is a Guid, so presume that when i call dict[guid] it always return an instance of my ObjectA (for the exemple)
public foo()
{
ObjecA objA = dict[guid];
objA.RWL.AcquireReaderLock(500);
if(objA.obj.TTL<=0)
{
objA.obj.RWL.AcquireWriterLock(1000);
objA.obj.Value = DateTime.Now().ToString();
objA.obj.RWL.ReleaseWriterLock();
}else{
int ttl = objA.obj.TTL;
Interlocked.Decrement(ref ttl);
}
objA.RWL.ReleaseReaderLock();
}
I am really not sure of my using of reader and writer over there, how did i need to use reader writer lock, with a conditional validation ?
Upvotes: 2
Views: 4574
Reputation: 46763
There are many problems with this code, including:
Interlocked.Decrement(ref objA.obj.TTL)
is how to do this properly.It also may be worth considering whether you really, really need to use reader/writer locks, instead of using something simpler like the lock{}
statement. Getting reader/writer locks right and avoiding deadlocks is hard even for developers who know these APIs and concepts really well, and even then they usually reserve their use for only the most performance-critical places (1000's+ per second). In other words, you may be better off starting out with a simpler approach using lock{}
, and only falling back to using ReaderWriterLockSlim
if performance is not acceptable.
As a starting point, I'd suggest you add some more info to your question:
I guarantee you that if you include this addiitonal info in your question, you'll get better answers which can help you out with any any remaining code issues. :-)
Upvotes: 7