相关疑难解决方法(0)

编写重试逻辑最干净的方法?

偶尔我需要在放弃之前多次重试一次手术.我的代码是这样的:

int retries = 3;
while(true) {
  try {
    DoSomething();
    break; // success!
  } catch {
    if(--retries == 0) throw;
    else Thread.Sleep(1000);
  }
}
Run Code Online (Sandbox Code Playgroud)

我想在一般的重试函数中重写它,如:

TryThreeTimes(DoSomething);
Run Code Online (Sandbox Code Playgroud)

在C#中有可能吗?该TryThreeTimes()方法的代码是什么?

.net c#

434
推荐指数
13
解决办法
20万
查看次数

有没有理由在现代.NET代码中使用goto?

我刚刚在.NET基础库的反射器中找到了这段代码......

    if (this._PasswordStrengthRegularExpression != null)
    {
        this._PasswordStrengthRegularExpression = this._PasswordStrengthRegularExpression.Trim();
        if (this._PasswordStrengthRegularExpression.Length == 0)
        {
            goto Label_016C;
        }
        try
        {
            new Regex(this._PasswordStrengthRegularExpression);
            goto Label_016C;
        }
        catch (ArgumentException exception)
        {
            throw new ProviderException(exception.Message, exception);
        }
    }
    this._PasswordStrengthRegularExpression = string.Empty;
Label_016C:
    ... //Other stuff
Run Code Online (Sandbox Code Playgroud)

我听说所有的"你都不会因为害怕流亡到永恒的地狱而使用goto".我总是高度重视MS编码员,虽然我可能不同意他们的所有决定,但我始终尊重他们的推理.

那么 - 这样的代码是否有充分的理由让我失踪?这个代码提取是由一个不合格的开发人员组装而成的吗?或.NET反射器返回不准确的代码?

我希望有一个很好的理由,而我只是一味地失踪了.

感谢大家的投入

.net c# goto

31
推荐指数
6
解决办法
4243
查看次数

在catch块中捕获异常后,是否可以再次在try块中执行代码?

我想在捕获异常后再次执行try块中的代码.这有可能吗?

对于Eg:

try
{
    //execute some code
}
catch(Exception e)
{
}
Run Code Online (Sandbox Code Playgroud)

如果异常被捕获,我想再次进入try块以"执行一些代码"并再次尝试执行它.

.net c# exception-handling exception

18
推荐指数
3
解决办法
3万
查看次数

标签 统计

.net ×3

c# ×3

exception ×1

exception-handling ×1

goto ×1