简体   繁体   English

如何在C#的特定时间运行代码

[英]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. 将在timer1_Tick()timer2_Tick()事件完成后执行(意味着timer1.Enabled = falsetimer2.Enable = false但我不知道该怎么做,能为您提供帮助吗?非常感谢。

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! 仅当两个事件的AutoReset都设置为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. BeginInvoke是必需的,因为事件可能在GUI线程之外的其他线程上运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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