c# - 多个线程(客户端)使用的列表集合
问题描述
我正在使用 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。请让我知道是否有更好的方法来满足我的需要。我知道该列表不是安全线程。有没有办法处理这个动作?如果我将使用锁定列表,我是否安全?
解决方案
你可以看看:
BlockingCollection
ConcurrentBag
在最简单的情况下,您可以使用对象变量并执行lock(object)
修改操作。
您还可以考虑不使用 linq,因为它有自己的开销并且速度很慢并且坚持使用 for 循环或 foreach 循环。
推荐阅读
- octobercms - 关系管理器不显示透视数据
- javascript - 单击也具有可单击事件的 div 下方的链接
- python - 具有多级列的 Pandas 数据框:重命名特定级别的列,使其与另一个级别相同
- regex - Typescrpt 正则表达式提取 x,y 位置
- automata - 自动机和可计算性
- c# - 完全递归爬虫不起作用。只有 2-3 个页面爬取深度
- node.js - create-react-app 后无法启动项目:错误:找不到模块“C:\Users\pcname\Documents\react-scripts\bin\react-scripts.js”
- mysql - 仅当子表中的外键在父表中具有分配给它的值时,才在子表中创建条目
- javascript - 如何使用按键阻止我的形状移动?
- json - 如何使用 Dart 中属性名称的枚举将 JSON 映射到对象