我正在开发一个发送命令并检查收到的答案的程序。我想实现一个功能,如果程序在一段时间内没有收到正确的答案,它会更改检查答案状态所需的bool。假设我在5秒内没有收到正确答案我将bool更改为false并停止寻找答案。
这是我的代码,我需要使用我的计时器
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
int bytes = COMport.BytesToRead;
byte[] buffer = new byte[bytes];
COMport.Read(buffer, 0, bytes);
SetText(ASCIIEncoding.ASCII.GetString(buffer));
if(Checked1 )
{
if(CheckBox_Port_CommandCheck_1.Checked)
Check_ReceivedAnswer(ASCIIEncoding.ASCII.GetString(buffer), TextBox_ExpectedAnswer_1.Text, PictureBox_Reply_1);
if (CheckBox_Port_CommandCheck_2.Checked)
Check_ReceivedAnswer(ASCIIEncoding.ASCII.GetString(buffer), TextBox_ExpectedAnswer_2.Text, PictureBox_Reply_2);
}
}
还有Check_ReceivedAnswer
功能
private void Check_ReceivedAnswer (string expectedA, string receivedA, PictureBox box)
{
if (receivedA.Contains(expectedA))
box.BackColor = Color.Green;
//Checked1 = false;
}
所以在我的DataReceivedHandler之后,如果我想查看经过的时间,如果它超过5秒,我想停止寻找答案。
答案 0 :(得分:0)
您需要异步运行计时器,当时间用完时更改值,如下所示:
// Create a 5 seconds timer
timer = new System.Timers.Timer(5000);
// Hook up the Elapsed event for the timer.
timer.Elapsed += OnTimedEvent;
timer.Enabled = true;
...
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
// Change your bool val to false
}
答案 1 :(得分:0)
如果你有异步方法,那么你可以使用
public async Task SendCommandAsync()
{
SendCommandToServer();
bool haveAnswer = false;
await Task.Delay(5000);
haveAnswer = IsAnwerHere();
if (!haveAnswer) {/* after 5 secs still no answer from server*/}
}
在同步方法的情况下(如果你不想停止调用者线程)
public void SendCommandSync()
{
SendCommandToServer();
bool haveAnswer = false;
Task.Delay(5000).ContinueWith(t =>
{
haveAnswer = IsAnwerHere();
if (!haveAnswer) {/* after 5 secs still no answer from server*/}
});
}
使用停止来电线程的同步方法
public void SendCommandSync()
{
SendCommandToServer();
bool haveAnswer = false;
Thread.Sleep(5000);
haveAnswer = IsAnwerHere();
if (!haveAnswer) {/* after 5 secs still no answer from server*/}
}
<强> UPD 强>
在你的情况下,它可以像smthg一样
private async void Check_ReceivedAnswer(string expectedA, string receivedA, PictureBox box)
{
await Task.Delay(5000);
if (receivedA.Contains(expectedA))
box.BackColor = Color.Green;
//Checked1 = false;
}
或即使您可以在来电功能中等待
private async void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
int bytes = COMport.BytesToRead;
byte[] buffer = new byte[bytes];
COMport.Read(buffer, 0, bytes);
SetText(ASCIIEncoding.ASCII.GetString(buffer));
if (Checked1)
{
await Task.Delay(5000);
if (CheckBox_Port_CommandCheck_1.Checked)
Check_ReceivedAnswer(ASCIIEncoding.ASCII.GetString(buffer), TextBox_ExpectedAnswer_1.Text, PictureBox_Reply_1);
if (CheckBox_Port_CommandCheck_2.Checked)
Check_ReceivedAnswer(ASCIIEncoding.ASCII.GetString(buffer), TextBox_ExpectedAnswer_2.Text, PictureBox_Reply_2);
}
}