【发布时间】:2012-11-26 01:32:45
【问题描述】:
我正在开发一个足球模拟器,我在不同的线程上有 9 场比赛的背景。在每个线程核心的方法中,都有一个事件。当这种情况发生时(当一个目标被“踢”时),我想用部分结果更新表单上的一个标签(名为goalLabel)。我写了一个代码……:
for (int i = 0; i < 6; i++)
{
if (i % 2 == 0) homeGoals++;
else awawyGoals++;
if (goal != null) goal(this); //(goal is an event)
Thread.Sleep(1000);
} //this is the full method
...在每个匹配中,目标的确切计数将是 6(结果将是 3 - 3),因此对于 9(9 也是固定的)背景匹配,goalLabel 应该更改文本(6* 9=)54 次。然而,它只改变了几次。 这是事件的事件处理方法:
public void GoalEventHandler(Match match)
{
string akt = string.Format("{0} {1} - {2} {3}", match.Opps[0].Name, match.Hgoals, match.Agoals, match.Opps[1].Name);
UpdateGoalLabel(akt);
}
还有 UpdateGoalLabel 方法:
public void UpdateGoalLabel(string update)
{
if (InvokeRequired)
{
MyDel del = new MyDel(UpdateGoalLabel); // yeah, I have a delegate for it: delegate void MyDel(string update);
Invoke(del, update);
}
else
{
lock (this) // if this lock isn't here, it works the same way
{
this.goalLabel.Text = update;
}
}
}
所以我可以访问并更改标签的文本,但我不知道为什么它不更改 54 次。这就是目标,在每个目标之后得到通知。
有什么想法吗?
提前谢谢你。
更新#1: 我用的是VS2010。
这是我启动线程的代码:
List<Thread> allMatches = new List<Thread>();
foreach (Match match in matches)
{
Thread newtmatch = new Thread(match.PlayMatch); //this is the first code block I wrote
allMatches.Add(newtmatch);
newtmatch.Start();
}
更新 #2: 这是我附加事件处理程序的地方(这是在相同的方法中,在前一个代码块上方几行):
matches = new List<Match>();
foreach (Team[] opponents in Program.cm.nextMatches)
{
Match vmi = new Match(opponents);
matches.Add(vmi);
vmi.goal += new Match.goalevent(GoalEventHandler);
}
//Program.cm.nextMatches is a List<Team[]> object that contains the pairs of teams for the next matches;
我将这些 Team 数组转换为 Match 对象,因为这个类有两个 Team 字段,并且有事件和 PlayMatch 方法,该方法仍然是包含(仅)第一个代码块的方法。
【问题讨论】:
-
您使用的是哪个版本的 C# VS2005、VS2010 等?还有,WinForms,WPF?最后,您能否展示一下您拥有的启动所有 9 个线程的代码,这些线程开始整个调用过程...
-
我使用的是VS2010,我用代码更新了“问题”。哦,它是一个 Windows 窗体。
-
你在哪里附加事件处理程序?
-
上面几行是我启动线程的地方。用同样的方法。查看更新2#。
-
更新#3:我尝试了一些东西:我声明了一个字符串列表,并且在哪里更新了goalLabel的文本(所以代码说:this.goalLabel.Text = update;)我添加了以下行:stringList.Add(update); //update 显然等于第二个代码块中的“akt”字符串 // 毕竟我在消息框中写出了这个 stringList 的全部内容,我得到了所有 54 个部分结果。所以这是WTF吗?代码中的两行之间没有任何内容,并且 stringList 正在更改和更新,而 goalLabel 没有。问题:为什么??
标签: c# label invokerequired background-thread