gpt4 book ai didi

c# - 代码没有遍历整个字典?

转载 作者:太空狗 更新时间:2023-10-30 01:15:37 25 4
gpt4 key购买 nike

我遇到了一个问题,但我不知道自己做错了什么。我尝试了无数不同的东西,但出于某种原因,它就是行不通。我的主循环:

static Dictionary<string, int> dict = new Dictionary<string, int>();

public static void IterateOverEachUser()
{
if (dict.Count > 0) {
foreach (KeyValuePair<string, int> item in dict.ToList())
{
string userName = item.Key;
int amountLeft = item.Value;
if(amountLeft == 60)
{
Log(userName + " started!");
}
Log(userName + amountLeft);
dict[userName] = dict[userName] - 1;
amountLeft = item.Value;
if(amountLeft == 0)
{
Log(userName + " ran out!");
}
}
}
}

public static void AddUser(string User)
{
if (dict.ContainsKey(User))
{
Log("User already exists.");
}
else
{
dict.Add(User,60);
Log("User has been added.");
}
}

我每 5 秒循环一次 IterateOverEachUser()。当我使用该方法添加一个用户时,一切都很好,但是当我添加第二个时,他的值停留在 60 而另一个不断滚动。

有人知道为什么会这样吗?我来自使用 HashMaps 的 Java,并使用相同的代码按预期工作。 (即:迭代每个用户,所有用户的值都减去 1,然后停止,直到 5 秒循环再次调用 IterateOverEachUser() 方法)。

提前致谢!

最佳答案

amountLeft = item.Value; 会产生错误的值(旧值)。

此外,在使用计时器和静态资源时,最好使用 lock 使您的方法线程安全

下面的测试代码非常适合我:

static Dictionary<string, int> dict = new Dictionary<string, int>();
static object lockObject = new Object();

public static void IterateOverEachUser()
{
lock (lockObject)
{
if (dict.Count > 0)
{
foreach (KeyValuePair<string, int> item in dict.ToList())
{
string userName = item.Key;
int amountLeft = item.Value;
if (amountLeft == 60)
{
Console.WriteLine(userName + " started!");
}
Console.WriteLine(userName + amountLeft);
dict[userName] = dict[userName] - 1;
amountLeft = dict[userName];
if (amountLeft == 0)
{
Console.WriteLine(userName + " ran out!");
}

Console.WriteLine("User " + item.Key + " = " + amountLeft);
}
}
}
}

public static void AddUser(string User)
{
if (dict.ContainsKey(User))
{
Console.WriteLine("User already exists.");
}
else
{
dict.Add(User, 60);
Console.WriteLine("User has been added.");
}
}

static void Main(string[] args)
{

AddUser("U1");
AddUser("U2");

int counter = 1;
System.Timers.Timer t1 = new System.Timers.Timer();
t1.Interval = 5000;
t1.Elapsed += (oo, ee) =>
{
IterateOverEachUser();

if (counter++ == 5)
AddUser("U3");
};

t1.Start();

Console.ReadKey();
}

输出:

User has been added.
User has been added.
U1 started!
U160
User U1 = 59
U2 started!
U260
User U2 = 59
U159
User U1 = 58
U259
User U2 = 58
U158
User U1 = 57
U258
User U2 = 57
U157
User U1 = 56
U257
User U2 = 56
U156
User U1 = 55
U256
User U2 = 55
User has been added.
U155
User U1 = 54
U255
User U2 = 54
U3 started!
U360
User U3 = 59
U154
User U1 = 53
U254
User U2 = 53
U359
User U3 = 58
U153
User U1 = 52
U253
User U2 = 52
U358
User U3 = 57
// and so one

关于c# - 代码没有遍历整个字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37404901/

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