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?