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

VB.NET 如何将布尔表达式传入函数内部执行以实现超时校验

实现通用带超时的条件测试函数

你需要借助Func(Of Boolean)委托实现延迟执行条件表达式,具体实现如下:

基础同步版本实现

' 支持自定义超时时间(默认10秒)、检查间隔(默认500毫秒)
Private Function TestCondition(condition As Func(Of Boolean), Optional timeoutMs As Integer = 10000, Optional checkIntervalMs As Integer = 500) As Boolean
    Dim sw As New Diagnostics.Stopwatch
    sw.Start()
    While sw.ElapsedMilliseconds < timeoutMs
        ' 每次循环才会实时计算条件表达式结果
        If condition.Invoke() Then
            sw.Stop()
            Return True
        End If
        System.Threading.Thread.Sleep(checkIntervalMs)
    End While
    sw.Stop()
    Return False
End Function

调用示例

' 基础判断:变量x是否等于5
Dim result1 = TestCondition(Function() x = 5)

' 文件存在判断:自定义超时为5秒
Dim result2 = TestCondition(Function() System.IO.File.Exists("myfile"), 5000)

' 复杂多条件判断
Dim result3 = TestCondition(Function() 
                                Return someObject.Status = OperationStatus.Success AndAlso anotherValue > 10
                            End Function)

实现原理

  • 传入的lambda表达式本质是匿名委托,不会在传参阶段计算结果,只有函数内部调用condition.Invoke()时才会实时计算当前条件的返回值,完全满足你需要在函数内部计算条件的需求。
  • 可以兼容所有返回布尔值的条件表达式,不需要为不同场景修改函数内部逻辑。

可选异步实现(不阻塞当前线程)

如果不希望等待条件期间卡住当前线程,可以使用异步版本:

Private Async Function TestConditionAsync(condition As Func(Of Boolean), Optional timeoutMs As Integer = 10000, Optional checkIntervalMs As Integer = 500) As Task(Of Boolean)
    Dim sw As New Diagnostics.Stopwatch
    sw.Start()
    While sw.ElapsedMilliseconds < timeoutMs
        If condition.Invoke() Then
            sw.Stop()
            Return True
        End If
        Await Task.Delay(checkIntervalMs)
    End While
    sw.Stop()
    Return False
End Function

' 异步调用方式
Dim result = Await TestConditionAsync(Function() x = 5)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 13:27:01