How to optimally implement locking that queues access to specific part of data?

92 views Asked by At

My ASP.NET application provides access to various chunks of data. Each chunk can be accessed by one or more users simultaneously, so the app must prevent conflicts.

After a lot of consideration, I'm thinking that optimistic concurrency is not the best solution for this scenario and currently looking at locking as a suitable option.

I can easily make all requests process one by one by using a SyncLock as follows:

Private Shared AccessLock As New Object

 SyncLock AccessLock

 ..Do some reading and writing here

 End Synclock

But that greatly limits the scalability of the application.

So I'm thinking of somehow enqueuing access to specific parts of data only. E.g. one queue is for accessing one part of data, and another queue for another part of data.

Is there a way to customize synchronization locking to use different queues for different parts of the data instead of just 1 queue for everything? I mean that it could allow me to manually specify something like "SyncLock ("Group1") and "SyncLock ("Group2").

2

There are 2 answers

2
Reed Copsey On

Is there a way to customize synchronization locking to use different queues for different parts of the data instead of just 1 queue for everything? I mean that it could allow me to manually specify something like "SyncLock ("Group1") and "SyncLock ("Group2").

Yes. You could have two separate objects, and SyncLock on the "Group1" object or the "Group2" object.

However, I would rethink your design. You may want to consider having one or more ConcurrentQueue(Of T) collections to hold your data. This will potentially let multiple threads access the data without taking locks, while remaining thread safe.

0
usr On

You can split your objects into groups, each of which you protect with a separate lock. This is called lock striping.

If you need to access more than one lock at a time you need to acquire them always in the same order or else you will get deadlocks.