-1

I'm making a program that repeats an action (for example a click) every n seconds.
My problem is that while Task.Delay() is running I can't interact with the program at all (the main issue is not being able to close it).

This is the function that I'm using as a timer :

private void timer(int time)
{
    var t = Task.Run(async delegate
    {
        await Task.Delay(time);
    });
    t.Wait();
}

The way I use it is for example :

int x = 10;
while(x-- > 0)
{
    MessageBox.Show("Test"); // display a messagebox
    timer(1000);             // 1 second delay
}

Is there a better way to delay an action or can I make it work this way?

Selman Genç
  • 100,147
  • 13
  • 119
  • 184

1 Answers1

1

Since you are calling Wait it blocks the UI thread until the task is complete. You will need to remove Wait from your code.

You can instead return the task from timer and await it in the while loop. This way the code will run asynchronously without blocking, but it requires you to add async to the method that contains your while loop.

There are already built-in timers in .NET framework, you can use one of them instead of reinventing the wheel.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184