简体   繁体   中英

How can I run a code at a specific time in C#

I have a code of button click event

private void bt_exchange_Click(object sender, EventArgs e)
{
    timer1.Start();
    timer2.Start();
    MessageBox.Show("Alice received Tb, Bob received Ta", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
    MessageBox.Show("They now have common Session Key", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
    key = ((Math.Min(Ta, Tb) == Tb) ? XpowYmodN(Tb, Sa, _p) : XpowYmodN(Ta, Sb, _p));
    tb_key_a.Text = tb_key_b.Text = key.ToString();
    Enable("key");
}

And I want that these code

MessageBox.Show("Alice received Tb, Bob received Ta", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
MessageBox.Show("They now have common Session Key", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
key = ((Math.Min(Ta, Tb) == Tb) ? XpowYmodN(Tb, Sa, _p) : XpowYmodN(Ta, Sb, _p));
tb_key_a.Text = tb_key_b.Text = key.ToString();
Enable("key");

will execute after timer1_Tick() and timer2_Tick() events finish (means that timer1.Enabled = false and timer2.Enable = false But I don't know how to do this, can you help me? Thank you very much.

Somewhere wen you initialize the timers:

timer1 += OnTimerElapsed;
timer2 += OnTimerElapsed;

And the methods:

delegate void CreateKeyDelegate();
static void OnTimerElapsed(Object source, System.Timers.ElapsedEventArgs e)
{
    if(!(timer1.Enabled || timer2.Enabled))
    {
        Control control; // any of your GUI controls!
        control.BeginInvoke(new CreateKeyDelegate(CreateKey));
    }
}

void CreateKey()
{
    // your code here
}

This will only work, if both events have AutoReset set to false! Else you would have to remember in separate booleans, if any of the timers fired already.

BeginInvoke is necessary as the event might run on another thread than your GUI thread.

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