I'm looking for a general purpose try and retry with a timeout in C#. Basically, I want the following:
bool stopTrying = false;
DateTime time = DateTime.Now;
while (!stopTrying)
{
try
{
//[Statement to Execute]
}
catch (Exception ex)
{
if (DateTime.Now.Subtract(time).Milliseconds > 10000)
{
stopTrying = true;
throw ex;
}
}
}
In the case above, I'm waiting for 10 second, but it should be a variable timeout based on a parameter. I don't want to have to repeat this full code wherever I need to use it. There are multiple places in my code where they isn't a timeout built into the API and I'll hit an exception if the application isn't ready for the statement to execute. This would also avoid having to hardcode delays in my application before these satement.
Clarification: The statement in question could be something like an assignment. If I use a delegate and method.Invoke, isn't the invokation scoped inside the delegate and not the original method?
Here's a simple solution:
Create a method that takes a lambda expression for Statement To Execute and a parameter for timeout. Inside that method execute the lambda expression inside the try / catch block and use parameter for the timeout.
It's not the prettiest thing, but I seems to work nicely so far. And it doesn't use exceptions to indicate a timeout.
UsageThis code is wrong (infinite loop):
The right one is:
Using your example, the solution is simple:
Just call
DoOrTimeout
with a delegate as the first parameter.Take a look at this question. What your asking for is exactly one of the uses I intended.
Implement C# Generic Timeout
WARNING: This sample uses Thread.Abort. Follow the link to my original question to read a few warnings about that in the comments.
Just run this in a loop with appropriate timeout control.