我正在製作一款足球模擬器,並且我在獨立線程上進行了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個線程,開始整個調用過程... – DRapp
我使用的是VS2010,我用代碼更新了「問題」。 哦,它是一個窗體。 – user1852051
你在哪裏附加事件處理程序? – akatakritos