我需要能够通过ID获取Project并安全地更改它的属性。我不是多线程的专家。所以,请帮助我。
public static class Application
{
private static ConcurrentDictionary<string, Project> projects = new ConcurrentDictionary<string, Project>();
private static readonly object locker = new object();
public static Project GetProjectByGuid(string guid)
{
if (guid == null) return null;
lock (locker)
{
return projects.GetValueOrDefault(guid, null);
}
}
public static void AddOrUpdateProject(Project project)
{
Project dbProject;
lock (locker)
{
dbProject = GetProjectByGuid(project.Guid);
if (dbProject == null)
{
projects[project.Guid] = project;
}
}
if (dbProject != null)
{
lock (dbProject.locker)
{
dbProject.Name = project.Name;
dbProject.Users = project.Users;
}
}
}
}
答案 0 :(得分:0)
由于Project对象不是线程安全的,因此您的问题的答案是否定的,您将无法使此线程安全。