I have the following script:
I am trying to block a thread in place if this "user" identifier of these threads matches the one that has already entered the lock code, but does not differ from the identifier.
I created some code examples to explain the behavior I want
class A { private static Dictionary<int, object> _idLocks = new Dictionary<int, object>(); private static readonly object _DictionaryLock = new object(); private int _id; private void A (int id) { _id = id; } private object getObject() { lock (_DictionaryLock) { if (!_idLocks.ContainsKey(_id)) _idLocks.Add(_id, new object()); } lock (_idLocks[_id]) { if (TestObject.Exists(_id)) return TestObject(_id); else return CreateTestObject(_id); } } }
Now it works 100% for what I expanded where the id of example 1 does not check if its object was created and another thread with id 1 is already busy creating this object.
But having two locks and a static dictionary does not seem to be the right way to do this at all, so I hope someone can show me an improved method to stop the stream from accessing the code only if this stream was created with the same id, since it is already taken code execution in the blocked section.
I was looking at the ReaderWriterLockSlim class, but that didnโt make sense to me because I donโt want the TestObject (id) object to be read at all while it is still being created.
I do not need to block the stream from accessing the dictionary. What I'm trying to avoid at all costs is the _id that runs this thread, should not be used inside CreateTestObject(_id) while it is already busy, because files are created and deleted with this identifier, which throws an exception if two threads try access the same files
This fix is โโwith a normal lock, but in this case I still need a thread where _id does not currently work inside the CreateTestObject(_id) method to be able to enter code inside the lock.
This is all because what happens inside CreateTestObject takes time and performance if the thread expects access to it.