开发者

VB.NET Calling BeginInvoke on another thread

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 a开发者_如何学运维nother 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


Your SafeInvoke method takes a Func(Of T, TResult).
That's a function that takes a T and returns a TResult.

Since x.Close() is a Sub and doesn't return anything, you can't make it into a Func(Of T, TResult).

You should make an overload that takes an Action(Of T) – a sub that takes a T and doesn't return anything.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜