Suppose I have a Queue of Tasks, and each Task have a locking object (syncObject) which controls shared resource access, Queue can have multiple Task which share same instances of syncObject. And I have N concurrent threads that should dequeue Tasks and proccess them in queue order, this means acquire lock on syncObject in the order of queue.
Code explanation:
abstract class Task
{
public readonly Object SyncObject = new Object();
}
Queue<Task> taskQueue = new Queue<Task>();
Object queueLock = new Object();
void TakeItemThreadedMethod()
{
Task task;
lock(queueLock) task = taskQueue.Dequeue();
//Between this lines is my problem,
//Other thread can dequeue next task and it may share same syncObject and
//acquire lock on it before this thread, thought this task was first in queue
lock(task.SyncObject)
{
//Do some work here
}
}
How to start proccessing Tasks (acquire Task.SyncObject lock) that share the same SyncObject in the order they were in Queue.