Karan Karan - 2 months ago 19
C# Question

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!

Answer

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 reccomend having tryMethod return a boolean and change it to

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