You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET中Delegate与Await机制及异步重试函数问题咨询

VB.NET异步重试函数的语法与类型疑问

我需要从网络获取URL内容,失败时重试2次,于是编写了接受委托的重试函数,用于在指定次数内重复执行操作直至成功。在调用和实现TryWithRetriesUntilAsync过程中遇到以下疑问:

  • 不理解ChatGPT建议添加Return Task.CompletedTask的原因,以及Task.CompletedTask的作用;
  • 单行异步Lambda表达式Async Function() result = Await func()的类型为Task(Of Boolean),而添加Return Task.CompletedTask的多行异步Lambda类型为Task(Of Task),不清楚类型差异的原因;
  • 预期传入Func(Of Task)类型,但实际传入的是Delegate Function类型,对此存在疑惑;
  • 多行版异步Lambda能正常运行,但单行版却无法工作,不理解语法差异导致的问题。

相关代码示例

基础调用示例

Dim jsonstring1 = Await jsonHelper.TryWithRetriesUntilAsync(
    Async Function()
        Await Task.Delay(1000)
        Return "hello world"
    End Function) 

实际使用场景示例

Dim jsonstring1 = Await jsonHelper.TryWithRetriesUntilAsync(
    Async Function() 
        Await GetContentFromSomeURL(url)
    End Function) 

重试函数实现

Public Shared Async Function TryWithRetriesUntilAsync(action As Func(Of Task), successCondition As Func(Of Boolean), Optional retries As Integer = 3, Optional delayMs As Integer = 2000) As Task
    For attempt As Integer = 1 To retries
        Try
            Await action()
        Catch ex As Exception
            Dim b = 1
            ' 可在此处记录异常
        End Try

        If successCondition() Then
            Exit For
        Else
            Await Task.Delay(delayMs)
        End If
    Next
End Function

Public Shared Async Function TryWithRetriesUntilAsync(func As Func(Of Task(Of String)), Optional retries As Integer = 2, Optional delayMs As Integer = 2000) As Task(Of String)
    Dim result = ""
    Await TryWithRetriesUntilAsync(Async Function() result = Await func(), Function() Not somethingIsWrong(result), retries, delayMs)
    Return result
End Function

ChatGPT建议修改后的代码

Await TryWithRetriesUntilAsync(
    Async Function()
        result = Await func()
        Return Task.CompletedTask
    End Function, 
    Function() Not somethingIsWrong(result), retries, delayMs)

类型测试代码

Public Shared Async Function TryWithRetriesUntilAsync(func As Func(Of Task(Of String)), Optional retries As Integer = 2, Optional delayMs As Integer = 2000) As Task(Of String)
    Dim result = ""
    Dim hello = Async Function() result = Await func()
    Dim hello1 = Async Function()
                     result = Await func()
                     Return Task.CompletedTask
                 End Function

运行差异示例

可正常运行的多行版

Await TryWithRetriesUntilAsync(Async Function()
                                   result = Await func()
                               End Function, Function() Not somethingIsWrong(result), retries, delayMs)

无法工作的单行版

Await TryWithRetriesUntilAsync(Async Function() result = Await func(), Function() Not somethingIsWrong(result), retries, delayMs)

内容的提问来源于stack exchange,提问作者user4951

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 07:05:59