我遇到了一个问题,我不知道自己做错了什么。我尝试了无数不同的东西,但由于某种原因,它只是赢了工作。我的主循环:
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()方法)。
提前致谢!
答案 0 :(得分:4)
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