代码之家  ›  专栏  ›  技术社区  ›  ariel

重试在vb.net中引发异常的语句的更好方法

  •  3
  • ariel  · 技术社区  · 15 年前

    我通常这样做:

        Dim Attempts = 0
        Try
    Retry:
            <Block>
        Catch
            If Attempts < 3 Then
                Attempts += 1
                Thread.Sleep(2000)
                GoTo Retry
            Else
                Throw
            End If
        End Try
    

    这对我来说真的很糟糕,但我不知道更好的方法。

    5 回复  |  直到 15 年前
        1
  •  2
  •   dr. evil    15 年前

    我觉得这是一个坏用法,我用这个,而且它更干净。

    Dim maxAttempt As Integer = 2
    
    For i As Integer = maxAttempt To 0 Step -1
    
     Try
        ...
        'Successful Quit
        Exit For
    
      Catch
         Thread.Sleep(2000)
    
      End Try
    Next 
    
        2
  •  3
  •   Alex Essilfie    15 年前

    您还可以尝试以下操作:

    Dim retryCount as Integer = 0
    Dim wasSuccessful as Boolean = False
    
    Do
        Try
            <statements>
            'set wasSuccessful if everything was okay.'
            wasSuccessful = True
        Catch
            retryCount +=1
        End Try
    Loop Until wasSuccessful = True OrElse retryCount >=5
    
    'check if the statements were unsuccessful'
    If Not wasSuccessful Then
        <do something>
    End If
    

    如果语句未成功,它将重试最多五次,但如果语句执行成功,它将立即退出循环。

        3
  •  2
  •   Jon Skeet    15 年前

    只使用一个 For 循环或A While 循环而不是 GoTo ,突破成功。但除此之外,这是正确的方法。

        4
  •  2
  •   jeroenh    15 年前

    从概念上讲,这是正确的方法,尽管我不会捕获每一个异常,但请参见@0xa3的答案。

    您可以通过将重试逻辑与实际代码分离,使其更“漂亮”,例如:

        Sub TryExecute(Of T As Exception)(ByVal nofTries As Integer, 
                                          ByVal anAction As Action)
            For i As Integer = 1 To nofTries - 1
                Try
                    anAction()
                    Return
                Catch ex As T
                    Thread.Sleep(2000)
                End Try
            Next
            ' try one more time, throw if it fails
            anAction()
        End Sub
    

    然后可以这样使用:

    TryExecute(Of SomeExceptionType)(3, Sub()
                                          <Block>
                                        End Sub())
    

    这只在vb 10中有效,如果使用.NET 3.5/vb 9,则需要在单独的函数中分离它。

        5
  •  1
  •   Dirk Vollmar    15 年前

    一般来说,应该非常仔细地考虑重试失败的内容。通常,最好报告错误并由用户决定。

    Raymond Chen给出了一个很好的例子,说明自动重试可能导致不需要的问题,并给出了避免重试的建议:

    Take it easy on the automatic retries