首页 > 解决方案 > 多个线程(客户端)使用的列表集合

问题描述

我正在使用 Asp Net 和一个列表集合。每个将在服务器中连接的客户端都会读取此列表。如果列表中存在他的ID-Name,它将修改或删除ID-Name 相等的列表行,否则如果ID-Name 不存在,则添加他的ID-Name。我将使用的唯一功能是

Add
Any
ForEach.List
RemoveAll

我不知道列表收集是否是好方法。我只想在服务器上快速处理,避免读取或写入数据库。

 public class Customers
    {
        public int CustomerID { get; set; }
        public string CustomerName { get; set; }
    }

    List<Customers> myCustomers = new List<Customers>();
    // POST: api/Customers
    public void Post([FromBody]string value)
    {

        //read incoming request 
        if (myCustomers.Any(x => x.CustomerName == "IncomingName"))
            myCustomers.RemoveAll(x => x.CustomerName == "IncomingName");

        else
            myCustomers.Add(new Customers { CustomerID = 1, CustomerName = "IncomingName" });

    }
}

服务器上的最大请求数将高达 2000。请让我知道是否有更好的方法来满足我的需要。我知道该列表不是安全线程。有没有办法处理这个动作?如果我将使用锁定列表,我是否安全?

标签: c#asp.net

解决方案


你可以看看:

  • BlockingCollection
  • ConcurrentBag

在最简单的情况下,您可以使用对象变量并执行lock(object)修改操作。

您还可以考虑使用 linq,因为它有自己的开销并且速度很慢并且坚持使用 for 循环或 foreach 循环。


推荐阅读