[英]How can I run a code at a specific time in C#
我有一個按鈕單擊事件的代碼
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");
}
我想要這些代碼
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");
將在timer1_Tick()
和timer2_Tick()
事件完成后執行(意味着timer1.Enabled = false
和timer2.Enable = false
但我不知道該怎么做,能為您提供幫助嗎?非常感謝。
您可以在某個地方初始化計時器:
timer1 += OnTimerElapsed;
timer2 += OnTimerElapsed;
以及方法:
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
}
僅當兩個事件的AutoReset都設置為false時,此方法才有效! 否則,如果任何一個計時器已觸發,則您必須記住使用單獨的布爾值。
BeginInvoke是必需的,因為事件可能在GUI線程之外的其他線程上運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.