假设我有一个任务队列,每个任务都有一个控制共享资源访问的锁定对象(syncObject),队列可以有多个共享相同同步对象实例的任务。而且我有 N 个并发线程应该使任务出队并按队列顺序处理它们,这意味着按队列顺序获取同步对象的锁定。
代码说明:
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
}
}
如何开始处理按队列中的顺序共享相同 SyncObject 的任务(获取 Task.SyncObject 锁)。