代码应在短暂延迟后执行一次 [英] Code should be executed one time after short delay

查看:23
本文介绍了代码应在短暂延迟后执行一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个定时器:

Timer delayTimer = new Timer();
delayTimer.Interval = 500;
delayTimer.Elapsed += (object sender, ElapsedEventArgs e) => {
    Console.WriteLine("test");
    textInputDialog.Show();
    delayTimer.Stop();
};
delayTimer.Start();

这里我有以下问题:

  • 计时器永不停止.代码每 500 毫秒执行一次.
  • textInputDialog.Show(); 不起作用(可能是上述问题的原因)
  • Timer never stops. Code is executed every 500ms.
  • textInputDialog.Show(); doesn't work (perhaps cause of problem above)

我的代码有什么问题?

替代解决方案:

这是 Jens Horstmann 提到的计时器的替代方案.这是在 UI 线程上调用的:

This is an alternative to timer as Jens Horstmann mentioned. And this is called on the UI thread:

private async Task SendWithDelay()
{
    await Task.Delay(500);
    textInputDialog.Show();
}

另一种选择是 NSTimer:

NSTimer.CreateScheduledTimer(new TimeSpan(0,0,0,0,500), delegate {
    textInputDialog.Show();
});

要在 UI 线程上调用调用,您可以使用 <代码>InvokeOnMainThread:

And to invoke a call on the UI thread you can use InvokeOnMainThread:

Timer delayTimer = new Timer();
delayTimer.Interval = 500;
delayTimer.Elapsed += (object sender, ElapsedEventArgs e) => {
    delayTimer.Stop();
    Console.WriteLine("test");
    InvokeOnMainThread (() => {
        textInputDialog.Show();
    });
};
delayTimer.Start();

推荐答案

在显示对话框之前停止计时器:

Stop the timer before you show the dialog:

delayTimer.Elapsed += (object sender, ElapsedEventArgs e) => {
    delayTimer.Stop();
    Console.WriteLine("test");
    textInputDialog.Show();
};

您也可能使用了错误的计时器.不要使用 System.Threading.TimerSystem.Timers ,因为这涉及多线程,它不适用于 winforms 或 WPF.(这可能是你的 MessageBox 没有显示的原因 - 它在错误的线程上调用)

Also you probably used the wrong timer. Don't use System.Threading.Timer or System.Timers because this involves multithreading which does not work well with winforms or WPF. (This is probably the reason your MessageBox does not show - its called on the wrong thread)

在 WPF 中你应该使用 System.Windows.Threading.DispatcherTimer

In WPF you should use System.Windows.Threading.DispatcherTimer

编辑

在 Winforms 中你应该使用 System.Windows.Forms.Timer(见评论)

In Winforms you should use System.Windows.Forms.Timer (see comments)

这篇关于代码应在短暂延迟后执行一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆