通用尝试和重试,在C#中的超时?

问题描述:

我在寻找一个通用的尝试和重试,在C#中的超时。基本上,我想以下内容:

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;
        }
    }
}

在上面的例子中,我等待10秒,但它应该是基于参数变量超时。我不想再重复这个充满code无论我需要使用它。有我在code多的地方,他们是不是建立在API超时,我会打的异常,如果应用程序是不是准备好要执行的语句。这也将避免在硬code拖延我的这些前语句应用程序。

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.

澄清:有关声明可能是这样的分配。如果我使用一个委托和method.Invoke,是不是原来的方法内的委托,而不是范围的invokation?

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?

使用您的示例,解决方法很简单:

Using your example, the solution is simple:

bool DoOrTimeout<T>(T method, TimeSpan timeout) where T : delegate // FIXME
{
    bool stopTrying = false;
    DateTime time = DateTime.Now;
    while (!stopTrying)
    {
        try
        {
            method.Invoke();
            stopTrying = true;
        }
        catch (Exception ex)
        {
            if (DateTime.Now.Subtract(time).Milliseconds > timeout.TotalMilliseconds)
            {
                stopTrying = true;
                throw;
            }
        }
    }
}

只需拨打 DoOrTimeout 与委托作为第一个参数。

Just call DoOrTimeout with a delegate as the first parameter.