Search code examples
c#methodsstopwatch

How to Call A Method after certain time has passed in C#


I'm trying to call an method in this if statement after a certain time (15 seconds) has ended, but it doesn't seem to work at all not print out the text in the method. How would I go about doing this, I have tried researching on how the stopwatch works but it doesn't seem to be working. Thank your for your help.

I have tried this code

    Stopwatch watch = Stopwatch.StartNew();

    if (watch.Elapsed.TotalMilliseconds == 15)
    {
       Method();
    }

Solution

  • Task is what you need

    Task.Delay(new TimeSpan(0, 0, 15)).ContinueWith(o => { Method(); });
    

    More about Asynchronous programming here