VB.NET 在另一个线程上调用 BeginInvoke
因此,从评论部分来看,此人的代码已在 http://www 上翻译为 VB.NET .codeproject.com/KB/cs/Threadsafe_formupdating.aspx 它显示了一些代码来帮助调用跨线程 UI 内容。
<System.Runtime.CompilerServices.Extension()> _
Public Function SafeInvoke(Of T As ISynchronizeInvoke, TResult)(ByRef isi As T, ByRef [call] As Func(Of T, TResult)) As TResult
If isi.InvokeRequired Then
Dim result As IAsyncResult = isi.BeginInvoke([call], New Object() {isi})
Dim endResult As Object = isi.EndInvoke(result)
Return DirectCast(endResult, TResult)
Else
Return [call](isi)
End If
End Function
当我尝试调用以下命令时,但出现错误:
Me.SafeInvoke(Function(x) x.Close())
或
frmLobby.SafeInvoke(Function(x) x.Close())
错误 1 扩展方法中类型参数的数据类型 'Public Function SafeInvoke(Of TResult)(ByRef call As System.Func(Of frmLogin, TResult)) 由于“GvE.Globals”中定义的“TResult”无法从这些参数中推断出来。显式指定数据类型可能会纠正此错误。 C:\GvE\GvE\frmLogin.vb 37 9 GvE
我缺少什么?我从表单中定义的方法内部调用该代码,但该方法是从另一个线程调用的。
只是试图避免委托,这就是上面的代码应该做的事情,但就是无法让它工作。
谢谢
So from the comments section where this persons code was translated to VB.NET on http://www.codeproject.com/KB/cs/Threadsafe_formupdating.aspx it shows a little code to aid in calling cross thread UI stuff.
<System.Runtime.CompilerServices.Extension()> _
Public Function SafeInvoke(Of T As ISynchronizeInvoke, TResult)(ByRef isi As T, ByRef [call] As Func(Of T, TResult)) As TResult
If isi.InvokeRequired Then
Dim result As IAsyncResult = isi.BeginInvoke([call], New Object() {isi})
Dim endResult As Object = isi.EndInvoke(result)
Return DirectCast(endResult, TResult)
Else
Return [call](isi)
End If
End Function
When I try to call the following however I get an error:
Me.SafeInvoke(Function(x) x.Close())
or
frmLobby.SafeInvoke(Function(x) x.Close())
Error 1 Data type(s) of the type parameter(s) in extension method 'Public Function SafeInvoke(Of TResult)(ByRef call As System.Func(Of frmLogin, TResult)) As TResult' defined in 'GvE.Globals' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error. C:\GvE\GvE\frmLogin.vb 37 9 GvE
What am I missing? I'm calling that code from inside a method defined in a form but that method is being called from another thread.
Just trying to avoid delegates and this is what the code above is supposed to do, but just can't get it to work.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的
SafeInvoke
方法采用Func(Of T, TResult)
。该函数接受
T
并返回TResult
。由于
x.Close()
是一个Sub
并且不返回任何内容,因此您不能将其变成Func(Of T, TResult).
您应该创建一个采用
Action(Of T)
的重载 - 一个采用T
且不返回任何内容的子函数。Your
SafeInvoke
method takes aFunc(Of T, TResult)
.That's a function that takes a
T
and returns aTResult
.Since
x.Close()
is aSub
and doesn't return anything, you can't make it into aFunc(Of T, TResult)
.You should make an overload that takes an
Action(Of T)
– a sub that takes aT
and doesn't return anything.