gpt4 book ai didi

c# - ConcurrentDictionary InvalidOperationException c#

转载 作者:太空宇宙 更新时间:2023-11-03 10:21:27 25 4
gpt4 key购买 nike

这是错误:

System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
at System.Collections.Generic.List1.Enumerator.MoveNextRare()<br/>
at System.Collections.Generic.List
1.Enumerator.MoveNext()
at System.Linq.Enumerable.WhereListIterator1.MoveNext()<br/>
at System.Linq.Enumerable.Count[TSource](IEnumerable
1 source)
Blockquote

我使用 web api 的静态字典

这是我用于我的 web api 的类:

public class UsersSecureProvider
{
public static ConcurrentDictionary<short, List<UserSecure>> _Users = new ConcurrentDictionary<short, List<UserSecure>>();

public bool Add(short Group, UserSecure Message)
{
try
{
var GetList = GetByKey(Group);

if (GetList != null)
{
GetList.Add(Message);
return Update(Group, GetList, GetList);
}
else
{
GetList = new List<UserSecure>();
GetList.Add(Message);
return Add(Group, GetList);
}
}
catch { }

return false;
}

private bool Add(short key, List<UserSecure> SendUser)
{
return _Users.TryAdd(key, SendUser);
}

public bool Remove(short Key)
{
List<UserSecure> listremove;
return _Users.TryRemove(Key, out listremove);
}

public List<UserSecure> GetByKey(short Group)
{
var listView = new List<UserSecure>();
if (_Users != null)
{
var getList = _Users.TryGetValue(Group, out listView);
}

return listView;
}

public bool Update(short Group, List<UserSecure> oldlist, List<UserSecure> newlist)
{
return _Users.TryUpdate(Group, newlist, oldlist);
}

public void Clear()
{
_Users.Clear();
}

public ConcurrentDictionary<short, List<UserSecure>> GetAll()
{
return _Users;
}

public bool UpdateListByUser(short Group, List<UserSecure> newlist)
{
var OldList = GetByKey(Group);
return _Users.TryUpdate(Group, newlist, OldList);
}
}

然后我给类(class)打电话

 var _providers = new UsersSecureProvider();

List<UserSecure> GetAll = _providers.GetByKey(1);

if (GetAll != null && GetAll.Any() && GetAll.Where(w => w.UserID == UserID && w.Key == UniqueSecure).Count() > 0)
{
result = true;
}
else
{
_providers.Add(1, new UserSecure { UserID = UserID, Key = UniqueSecure });
}

为什么我会收到这个错误异常?

谢谢。

最佳答案

这个:

List<UserSecure> GetAll = _providers.GetByKey(1);

返回对基础集合的引用。对列表的相同引用可能正在通过您拥有的其他 WebAPI 操作之一进行修改。您不能同时枚举和修改 List<T> .

相反,创建一个新的 List<T>并列举它:

List<UserSecure> GetAll = _providers.GetByKey(1).ToList();

关于c# - ConcurrentDictionary InvalidOperationException c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33315791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com