简体   繁体   中英

What is the best way to change bool state after elapsed time?

I'm working on a program which sends commands and checks the received answer. I want to implement a feature where if the program doesn't receive the correct answer in some amount of time it changes the bool which is needed to check the state of the answer. Lets say I do not receive the correct answer in 5 seconds i change the bool to false and stop looking for an answer.

Here's my code where I need to use my timer

        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);
        }



    }

Also there's the the Check_ReceivedAnswer function

    private void Check_ReceivedAnswer (string expectedA, string receivedA, PictureBox box)
    {

        if (receivedA.Contains(expectedA))
            box.BackColor = Color.Green;
        //Checked1 = false;
    }

So in my DataReceivedHandler after the first if I want to check the elapsed time and if it's more that 5 secs i want to stop looking for the answer.

You need to run a timer asynchronously, and when time runs out change the value, something like this:

// 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
}

if you have async method then you can use

public async Task SendCommandAsync()
{
    SendCommandToServer();  
    bool haveAnswer = false;
    await Task.Delay(5000); 
    haveAnswer = IsAnwerHere();

    if (!haveAnswer) {/* after 5 secs still no answer from server*/}
}

In case of sync method (and if you dont want to stop caller thread)

public void SendCommandSync()
{
    SendCommandToServer();
    bool haveAnswer = false;
    Task.Delay(5000).ContinueWith(t =>
    {
        haveAnswer = IsAnwerHere();

        if (!haveAnswer) {/* after 5 secs still no answer from server*/}
    }); 
}

Sync method with stopping caller thread

public void SendCommandSync()
{
    SendCommandToServer();
    bool haveAnswer = false;
    Thread.Sleep(5000);
    haveAnswer = IsAnwerHere();

    if (!haveAnswer) {/* after 5 secs still no answer from server*/}    
}

UPD

In you case it can be smthg like

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;
}

OR even you can wait in caller function

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM