Search code examples
c#timeout

Implementing a timeout in c#


I am new to c#; I have mainly done Java.

I want to implement a timeout something along the lines:

int now= Time.now();
while(true)
{
  tryMethod();
  if(now > now+5000) throw new TimeoutException();
}

How can I implement this in C#? Thanks!


Solution

  • One possible way would be:

    Stopwatch sw = new Stopwatch();
    sw.Start();
    
    while(true)
    {
        tryMethod();
        if(sw.ElapsedMilliseconds > 5000) throw new TimeoutException();
    }
    

    However you currently have no way to break out of your loop. I would recommend having tryMethod return a bool and change it to:

    Stopwatch sw = new Stopwatch();
    sw.Start();
    
    while(!tryMethod())
    {
        if(sw.ElapsedMilliseconds > 5000) throw new TimeoutException();
    }