我有以下情况:
一个单例类,我们称它为 Coordinator,它有多个线程正在加入。该类的作用是以线程安全的方式“初始化”某个实体(EntityObject)。假设我们有 5 个线程试图初始化一个 EntityObject。应该只允许一个线程来初始化 EntityObject,而其他 4 个线程应该等到初始化完成。EntityObject 的名称是唯一的。
下面是一些代码来说明这一点:
public class EntityObject
{
public EntityObject()
{
IsInitialized = false;
Name = string.Empty;
}
public bool IsInitialized { get; set; }
public string Name { get; set; }
}
public class InitializeArguments
{
public EntityObject Entity { get; set; }
}
public class Coordinator
{
public void initialize(InitializeArguments args)
{
if (!args.Entity.IsInitialized)
{
//initializeCode goes here
//only one thread is allowed to initialize an EntityObject with a certain Name
//the other threads have to wait until initialization is done
args.Entity.IsInitialized = true;
}
}
}
class Program
{
static void Main(string[] args)
{
List<Task> allTask = new List<Task>();
Coordinator coordinator = new Coordinator();
EntityObject entity1 = new EntityObject() { IsInitialized = false, Name = "entity1" };
EntityObject entity2 = new EntityObject() { IsInitialized = false, Name = "entity2" };
EntityObject entity3 = new EntityObject() { IsInitialized = false, Name = "entity3" };
for (int i = 0; i < 4; i++)
{
var task = Task.Factory.StartNew(() =>
{
InitializeArguments initArg = new InitializeArguments() { Entity = entity1 };
coordinator.initialize(initArg);
});
allTask.Add(task);
}
for (int i = 0; i < 4; i++)
{
var task = Task.Factory.StartNew(() =>
{
InitializeArguments initArg = new InitializeArguments() { Entity = entity2 };
coordinator.initialize(initArg);
});
allTask.Add(task);
}
for (int i = 0; i < 4; i++)
{
var task = Task.Factory.StartNew(() =>
{
InitializeArguments initArg = new InitializeArguments() { Entity = entity3 };
coordinator.initialize(initArg);
});
allTask.Add(task);
}
Task.WaitAll(allTask.ToArray());
Console.ReadLine();
}
}
在这种情况下,entity1,entity2,entity3 应该只初始化一次。
我正在考虑使用 a Dictionary<string, ManualResetEventSlim>
来实现这一点,但我无法让它发挥作用。