-1

I need to be able to get the Project by ID and safely change the properties of it. I am not the specialist in multi-threading. So, please, help me with this.

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;
            }
        }
    }
}
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
  • 1
    The use of a ConcurrentDictionary means you shouldn't need to add lock objects to your methods when interacting with the dictionary – oppassum Feb 01 '18 at 19:07
  • You have to run some test cases to verify your codes first. – Sphinx Feb 01 '18 at 19:07
  • yes, but Project object is not thread-safe – Yevheniy Tymchishin Feb 01 '18 at 19:08
  • If `Project` is not thread safe then no amount of locking around the dictionary it's stored in will make it thread safe. If two threads have a reference to the same `Project` then it doesn't matter how they got it. You would either want to ensure that multiple threads don't both interact with the same `Project` instance or make `Project` thread safe. – Scott Hannen Feb 01 '18 at 19:14

1 Answers1

0

Since the Project object is not thread safe, the answer to your question is no, you will not be able to make this thread safe.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175