0

In my application, I need to delay the execution of a method for some time. For that I have used System.Windows.Forms.Timer.

I have used the below code to initialize and start the timer.

Timer timer = new Timer();
timer.Tick += Timer_Tick;
timer.Interval = 3000;
timer.Start();

In the Timer.Tick event I have called the method which should be delayed as given below.

 private void Timer_Tick(object sender, EventArgs e)
    {
        DoSomethingElse();
        timer.Stop();
    }

This works perfectly, but I don't know whether it is the exact method to delay the execution.

Is there any other efficient way to achieve this?

TarHalda
  • 1,050
  • 1
  • 9
  • 27
  • 1
    There are many possible ways to delay execution of some code. Which is best depends on context, which you haven't provided. The marked duplicate will provide some insight regarding comparison of blocking a thread (e.g. with `Thread.Sleep()`) and using some form of asynchronous signaling/callback (e.g. with one of the several timer classes .NET offers). A modern C# idiom not addressed in the duplicate would be to use an `async` method and `await Task.Delay(...)`. – Peter Duniho Mar 03 '17 at 08:19
  • 1
    See also e.g. https://stackoverflow.com/questions/4705535/how-to-delay-program-for-a-certain-number-of-milliseconds-or-until-a-key-is-pre and https://stackoverflow.com/questions/10963465/how-to-call-a-method-after-so-many-seconds – Peter Duniho Mar 03 '17 at 08:19

3 Answers3

0

you could start a task and delay, however, the way you are doing it, you will get a callback on your UI thread so you can interact with windows forms ok if that's what your delayed function does.

Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156
0

You can use Thread.Sleep() in .Net 4.0. But, It will block the current thread.

Sudharsan
  • 11
  • 4
-3

Try using Task.Delay. You can use it like this:

Task.Delay(1000).Wait();
DoSomething();

Hope it helps!

mindOfAi
  • 4,412
  • 2
  • 16
  • 27