C# system.timers.timer 奇怪的行为



我正在尝试实现欺凌协调员选举算法。在此算法中,协调器每 10 秒发送一次活动消息,所有进程至少等待 14 秒才能接收活动消息,如果它们在该时间内没有收到消息,它们将启动死协调器选择。

问题是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++;
}
}

完整的代码可以在这里找到 欺凌算法

注意:我使用无源服务器只是为了广播来自每个进程的消息

我不知道是什么导致了问题,但我认为如果您记录启动和停止所有方法并分析输出,您将能够快速找出原因。

这将有助于确定是否: 1.正如@Idle_Mind所建议的,您正在添加越来越多的处理程序 2. 执行每个方法所花费的时间逐渐增加 以及更多...

我不知道您的应用程序是如何构建的,但您甚至可以从Console.WriteLineDebug.WriteLine开始。

最新更新