此 C# 代码可以在线程安全模式下工作吗?

Will this C# code work in thread-safe mode?

我需要能够通过 ID 获取项目并安全地更改它的属性。我不是多线程方面的专家。所以,请帮我解决这个问题。

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;
            }
        }
    }
}

由于Project对象不是线程安全的,所以你的问题的答案是否定的,你将无法使这个线程安全。