C# 使用 Timer 将操作延迟几秒钟

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19388517/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:52:34  来源:igfitidea点击:

Using Timer to delay an operation a few seconds

c#timer

提问by user2214609

I am trying to delay my method by using a timer:

我试图通过使用计时器来延迟我的方法:

private System.Timers.Timer _delayTimer;

    private void delay()
    {
          _delayTimer = new System.Timers.Timer();
          _delayTimer.Interval = 5000;
          //_delayTimer.Enabled = true;
          _delayTimer.Elapsed += _delayTimer_Elapsed;
          _delayTimer.Start();
          someMethod();
        }
    }

    private void _delayTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        // delay for 5 seconds
    }

When i am get into delay()method i want to start the timer, than i want the 5 seconds delay and only after that i want to execute someMethod()and currently this not happen, after execute delay()the someMethod()executed without 5 seconds delay

当我进入delay()方法我想开始计时,比我想的延时5秒,之后才是我想要执行someMethod(),目前这不会发生,执行后delay()someMethod()无延时5秒执行

采纳答案by Jon

Your current code sets up the timer and then immediately executes someMethod. Instead of this, you need to put the actual method call inside your Elapsedhandler:

您当前的代码设置计时器,然后立即执行someMethod。取而代之的是,您需要将实际的方法调用放入您的Elapsed处理程序中:

private void delay()
{
      _delayTimer = new System.Timers.Timer();
      _delayTimer.Interval = 5000;
      //_delayTimer.Enabled = true;
      _delayTimer.Elapsed += _delayTimer_Elapsed;
      _delayTimer.Start();
    }
}

private void _delayTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
      someMethod();
}

And if there's nothing else you intend to do you can simply write this inline:

如果您没有其他打算,您可以简单地编写以下内联:

_delayTimer = new System.Timers.Timer();
_delayTimer.Interval = 5000;
_delayTimer.Elapsed += (o, e) => someMethod();
_delayTimer.Start();

回答by Servy

You need to call someMethodin the timer's Elapsed handler:

您需要调用someMethod计时器的 Elapsed 处理程序:

private void delay()
{
      _delayTimer = new System.Timers.Timer();
      _delayTimer.Interval = 5000;
      _delayTimer.AutoReset = false; //so that it only calls the method once
      _delayTimer.Elapsed += (s,args) => someMethod();
      _delayTimer.Start();
}

You could also use Task.Delayinstead:

您也可以Task.Delay改用:

private void delay()
{
    Task.Delay(5000)
    .ContinueWith(t => someMethod());
}

回答by Sriram Sakthivel

If you're in .Net4.5(or using BCL.Async pack) you can use Task.Delay

如果您使用 .Net4.5(或使用 BCL.Async 包),您可以使用 Task.Delay

private async void delay()
{
    await Task.Delay(5000);
    someMethod();
}

If you're under .Net4.5

如果您使用的是 .Net4.5

Try the below code. I'll suggest you to use System.Threading.Timer

试试下面的代码。我会建议你使用System.Threading.Timer

var timer = new System.Threading.Timer(x => someMethod(), null, 5000, System.Threading.Timeout.Infinite);\

Don't forget when you use Threading.Timer someMethodwill be invoked in ThreadPoolthread, If you're accessing UI you need to marshal the call to UI thread.

不要忘记当您使用 Threading.Timer 时someMethod将在ThreadPool线程中调用,如果您正在访问 UI,则需要将调用编组到 UI 线程。

回答by Jim Mischel

If you want the current thread to pause for five seconds, then call Thread.Sleep. For example:

如果您希望当前线程暂停五秒钟,则调用Thread.Sleep. 例如:

Thread.Sleep(TimeSpan.FromSeconds(5));
DoSomething();

Use a timer if you want something to happen five seconds from now, while you're doing something else. When the timer elapses, the action will be executed on a thread pool thread.

如果您希望从现在起五秒钟后发生某事,而您正在做其他事情,请使用计时器。当计时器结束时,该操作将在线程池线程上执行。

Also, if you only want the timer to execute one time (rather than once every five seconds), be sure to set AutoResetto false.

此外,如果您只想让计时器执行一次(而不是每五秒一次),请务必将AutoReset设置为false

回答by kazem

System.Threading.Tasks.Task.Factory.StartNew(() =>
            {
                System.Threading.Thread.Sleep(5000);
                /*
                 * Here Yopur code to do some method :D
                 * */
            });