1

I'm trying to get a specific piece of code to repeat.

I would like it so that when I press a button, it opens an application and then closes it 10 seconds later, only to reopen it again. I believe I would have to use 2 timers, but I still can't figure out what code I should use to set an on timer end (or something like that) to run the specified code.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Bizzie
  • 47
  • 8
  • @TheGeneral understood, thank you. – Bizzie Aug 06 '20 at 01:14
  • That seems correct, use a `Timer` with `AutoReset = true`. One important thing to have in mind is that the UI is handled by a separate thread than your code, so you need to drop a `Timer` in the main form and use that one. Do not create a `Timer` manually in your code. Clarification needed: do you need the application to close after 10s, then open again immediate, or also after 10s? And then all over again in an endless loop? – Andrew Aug 06 '20 at 01:27
  • @Andrew Thanks for the response. I would need the code to open an external application (I have this already), then wait 10 seconds then close, and immediately reopen. – Bizzie Aug 06 '20 at 01:46
  • And where is the code that repeats every x second? What you are saying just happens once, with a delay in the middle. Do you have the code to close the application? – Andrew Aug 06 '20 at 01:51

1 Answers1

3

If you make your click handler async you can just use Task.Delay.

public async void MyButton_Click(object sender, EventArgs 3)
{
    OpenApplication();
    await Task.Delay( 10 * 1000 ); //10,000 milliseconds a.k.a. 10 seconds
    CloseApplication();
    OpenApplication();
}

If you don't know how to "close" an application, see this related question.

John Wu
  • 50,556
  • 8
  • 44
  • 80
  • I'd use `Task.Delay(TimeSpan.FromSeconds(10))`, then it's really clear how long the delay is. – Idle_Mind Aug 06 '20 at 02:08
  • While I agree that the `FromSeconds` is marginally clearer, I think that specifying a number of milliseconds is clear enough, and not worth the creation of an object, especially if then internally `Task.Delay(TimeSpan)` is just an overload that ends up calling the millisecond one. If any developer has difficulties understanding this approach, we have a bigger issue. :P – Andrew Aug 06 '20 at 02:37