0
我想實施欺負協調員選舉算法。在該算法中,協調器每10秒發送一次活動消息,所有進程至少等待14秒才能接收活動消息,如果他們在那段時間內沒有收到消息,他們將啓動死選協調器選舉。C#system.timers.timer奇怪的行爲
問題是AliveTimer(Timer3_Count)正在呈指數級增長,活動進程也在影響它。我不知道它爲什麼表現怪異。
當初始協調者發送Alive消息時,計數器工作正常,但是在死選協調員選舉後,其行爲異常。
else if (Received_Text.Contains("Alive:"))
{
SetText(Received_Text + "\n");
Coordinator_Alive = true;
Timer3_Counter = 0;
if (Alive_Count == 0)
{
Alive_Count++;
AliveTimer.Interval = (1 * 1000);
AliveTimer.Enabled = true;
AliveTimer.Elapsed += new System.Timers.ElapsedEventHandler(AliveTimer_Elapsed);
AliveTimer.Start();
}
}
逝去的功能在這裏 我覺得有什麼不對我的計劃,我都試過了。
private void AliveTimer_Elapsed(object sender, EventArgs e)
{
Timer3_Counter++;
SetTimer(Timer3_Counter.ToString());
Random rnd = new Random();
int rand_time = rnd.Next(14, 18);
if (Timer3_Counter == 14)
{
AliveTimer.Stop();
Timer3_Counter = 0;
Alive_Count = 0;
if (Coordinator_Alive == false)
{
byte[] buffer = Encoding.ASCII.GetBytes("Dead Coordinator Election: " + txName.Text);
_clientSocket.Send(buffer);
Timer4_Counter = 0;
DeadTimer.Interval = (1 * 1000);
DeadTimer.Elapsed += new System.Timers.ElapsedEventHandler(DeadTimer_Elapsed);
DeadTimer.Enabled = true;
DeadTimer.Start();
}
}
if (Coordinator_Alive == true)
Coordinator_Alive = false;
}
和死者協調員選碼是這裏
else if (Received_Text.Contains("Dead Coordinator Election:"))
{
SetCPID("");
Coordinator_Alive = false;
Alive_Count = 0;
Timer3_Counter = 0;
AliveTimer.Stop();
AliveTimer.Enabled = false;
string output = Regex.Match(Received_Text, @"\d+").Value;
SetText("Dead Coordinator Election Received from Process ID: " + output + "\n");
if (Convert.ToInt32(txName.Text) > Convert.ToInt32(output))
{
byte[] buffer = Encoding.ASCII.GetBytes("Greater Process No: " + txName.Text + " found than " + output + "\n");
_clientSocket.Send(buffer);
SetText("Our Process No: " + txName.Text + " is Greater than " + output + "\n");
Lower_Count++;
byte[] buffer1 = Encoding.ASCII.GetBytes("Dead Coordinator Election: " + txName.Text);
_clientSocket.Send(buffer1);
}
else
{
byte[] Txt_Send = Encoding.ASCII.GetBytes("Our Process No: " + txName.Text + " is less than " + output);
_clientSocket.Send(Txt_Send);
Greater_Count++;
}
}
完整的代碼可以在這裏找到 Bully Algorithm
注:我使用的被動式服務器只是廣播從每個進程
消息
_問題是AliveTimer(Timer3_Count)正在呈指數級增長,並且活動進程也在影響它。我不知道它爲什麼表現怪異。你幾乎肯定會多次連接'Elapsed()'處理程序。這會導致您的代碼每次「tick」運行多次。你應該只在一次**之前連接那個處理程序**,通常在你創建它的時候。 –
當我停止並重新啓動計時器時,它開始多次滴答滴答。 如何避免這種情況? – Mayur
...以及你如何停止並啓動計時器?請告訴我們該代碼。 –