我在VB .net 2008中有以下代码示例
Public Function CheckPathFunction(ByVal path As String) As Boolean
Return System.IO.File.Exists(path)
End Function
Public Function PathExists(ByVal path As String, ByVal timeout As Integer) As Boolean
Dim exists As Boolean = True
Dim t As New Thread(DirectCast(Function() CheckPathFunction(path), ThreadStart))
t.Start()
Dim completed As Boolean = t.Join(timeout)
If Not completed Then
exists = False
t.Abort()
End If
Return exists
End Function
不幸的是,我必须使用Vb .net 2005和net framework 2.0;如何在VB .net 2005中完成相同的操作?,VB .net 2005不支持与代码行num对应的语法。 3:
Function() CheckPathFunction(path)
请注意,要调用的函数需要一个参数并返回一个值
我已尝试使用下一个指示但不起作用的代理
Private Delegate Function CheckPath(ByVal path As String) As Boolean
Public Function CheckPathFunction(ByVal path As String) As Boolean
Return IO.File.Exists(path)
End Function
Public Function PathExists(ByVal path As String, ByVal timeout As Integer) As Boolean
Dim checkPathDelegate As New CheckPath(AddressOf CheckPathFunction)
Dim exists As Boolean = True
Dim t As New Thread(checkPathDelegate(path))
t.Start()
Dim completed As Boolean = t.Join(timeout)
If Not completed Then
exists = False
t.Abort()
End If
Return exists
End Function
由于
答案 0 :(得分:2)
使用ParameterizedThreadStart Delegate调用Thread构造函数时,请参阅this MSDN article。既然你在VB中,你应该能够做到这一点:
Dim t As New Thread(AddressOf CheckPathFunction)
t.Start(path)
嗯,这就是启动线程的答案。但我同意SteveDog的看法,即只要线程完成或超时,它实际上并不会返回文件是否存在。
编辑返回值: 获得该值的一种方法是传入一个对象,而不仅仅是路径。然后使用该对象传回结果。
所以宣布一个类,如:
Class DataHolder
Public Path As String
Public Found As Boolean
End Class
更改CheckPathFunction,如:
Public Sub CheckPathFunction(ByVal rawData As Object)
Dim data As DataHolder = DirectCast(rawData, DataHolder)
data.Found = System.IO.File.Exists(data.Path)
End Sub
并改变PathExists,如:
Public Function PathExists(ByVal path As String, ByVal timeout As Integer) As Boolean
Dim exists As Boolean
Dim t As New Thread(AddressOf CheckPathFunction) ' (DirectCast(Function() CheckPathFunction(path), ThreadStart))
Dim data As DataHolder = New DataHolder
data.Path = path
t.Start(data)
Dim completed As Boolean = t.Join(timeout)
If Not completed Then
exists = False
t.Abort()
Else
exists = data.Found
End If
Return exists
End Function
答案 1 :(得分:1)
以@eol作为基本结构的代码,最终的工作代码是:
Class KeyValuePair
Public Path As String
Public Found As Boolean
End Class
Public Sub CheckPathFunction(ByVal dataObject As Object)
dataObject.Found = IO.Directory.Exists(dataObject.Path)
End Sub
Public Function PathExists(ByVal path As String, ByVal timeout As Integer) As Boolean
Dim exists As Boolean
Dim data As New KeyValuePair
data.Path = path
Dim t As New Thread(New ParameterizedThreadStart(AddressOf CheckPathFunction))
t.Start(data)
Dim completed As Boolean = t.Join(timeout)
If Not completed Then
exists = False
t.Abort()
Else
exists = data.Found
End If
Return exists
End Function