I have a list of "Module" classes, List<Module> modules. These modules each contain their own public object to use as a lock when accessing data. Let's say I have a couple threads which perform processing on these modules at random times. Currently I have each thread perform the processing on the modules in order, like so:
foreach (Module module in modules)
{
lock (module.Locker)
{
//Do stuff
}
}
This has worked fine so far, but I have the feeling there's a lot of unnecessary waiting. For instance, if two threads start one right after another, but the first is performing heavy processing and the second one isn't, the second one will have to wait on every module while the first one is doing its processing.
This is the question then: Is there a "proper" or "most efficient" way to lock on elements in a list? I was going to do this:
foreach (Module module in modules.Randomize())
{
lock (module.Locker)
{
//Do stuff
}
}
Where "Randomize()" is just an extension method that returns the elements of the list in a random order. However, I was wondering if there's an even better way than random?
ReaderWriterLockSlim