C#ConcurrentDictonary在集合中设置除密钥之外的值

时间:2017-11-02 00:49:46

标签: c#-4.0

请在关闭之前查看我的代码。

下面的代码有效,但看起来非常黑,我正在寻找有关使用更清晰的代码实现同样的事情的建议,或者它是如此好。

调用Add和Remove的代码将来自可能同时访问代码的不同线程,因此它必须保持线程安全。

using System;
using System.Collections.Concurrent;

namespace Server
{
    public class Company
    {
        public string Name { get; set; }
        public string Address { get; set; }
        public string Phone { get; set; }
        public ConcurrentDictionary<string, Employee> Employees = new ConcurrentDictionary<string, Employee>();
    }

    public class Employee
    {
        public string First { get; set; }
        public string Last { get; set; }
        public string Ext { get; set; }
    }

    public class Clients
    {
        public ConcurrentDictionary<string, Company> CompaniesDict = new ConcurrentDictionary<string, Company>();


        public bool Add_Company(string ID, string Name, string Address, string Phone) //This function works
        {

            Company MyCompany = new Company();
            Employee MyEmployees = new Employee();

            MyCompany.Name = Name;
            MyCompany.Address = Address;
            MyCompany.Phone = Phone;
            MyCompany.Employees = MyEmployees;

            return CompaniesDict.TryAdd(ID, MyCompany);

        }

        public bool Remove_Company(string ID) //This function works
        {

            return CompaniesDict.TryRemove(ID, Company tCompany);

        }

        //This is were I need the help this seems so hacked. Im not trying to update the key, but the value intstead
        public bool Set_CompanyName(string ID, string Name) 
        {

            CompaniesDict.TryGetValue(ID, out Company oCompany);

            Company nCompany;
            nCompany = oCompany;
            nCompany.Name = Name;

            return CompaniesDict.TryUpdate(ID, nCompany, oCompany);
        }

        public string Get_CompanyName(string ID)
        {

            CompaniesDict.TryGetValue(ID, out Company tCompany);

            return tCompany.Name;
        }


    }
}

请不要关闭它并将我链接到一些你称之为重复的无用代码。很抱歉这么直率,但最近这个网站的编码员发生了这件事。如果您有任何问题我可以回答,以便您可以全力帮助我,请询问他们。

先谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

当您更新对象上的字段时,有一种更简单的方法。 请注意,我当前的PC上没有安装C#,因此无法对此进行验证。

请注意,我声明了out参数,但是不构造一个会立即销毁的新参数,而是修改了对象本身。 即

Company company; 

公司公司=新公司();

如果多个线程调用SetCompanyName(),这仍然不是确定性的,因为新的名称在活动对象上更新,并且可能存在潜在的竞争条件。但是,添加和删除将是,即使在删除名称更新之前删除了公司实例。

public bool Set_CompanyName(string ID, string Name) 
{
   Company company; 
   var retval= CompaniesDict.TryGetValue(ID, out company)
   if (retval) {
       company.Name=Name; // Update your company object directly
    }
//else Do something such as throw an exception if it's not found
    return retval;
 }