开发者

Delegates in VB - how to from C#?

I'm stuck on converting this C# code to VB:

AsyncHelpers.Async.Do(delegate { WriteStuff("additional stuff..."); });

I was thinking it would be something like

AsyncHelpers.Async.Do(Function() WriteStuff("additional stuff...")

but I get the error "Expression does not produce a value".

Can someone please give me the appropriate VB.Net translation?

Thanks.

========== UPDATE

开发者_Python百科.
. 
. 

             Async.Do(New DlgR(AddressOf WriteStuff))


        End Sub

        Friend Shared Sub WriteStuff(ByVal thisStr As String)
            'do stuff with thisStr

        End Sub

Based on Brian's suggestion below, this still doesn't work.

How do I get the parameter passed to WriteStuff?

Lastly, I'm also getting signature compatibility error with delegate function DlgR() as object.


VB.Net doesn't do a very good job supporting lambda expressions (see Use Lambda Expression within ASP.NET MVC View using VB.NET).

You can try something like this...

Sub Main()
    Async.Do(New DlgR(AddressOf WriteStuff))
End Sub
Public Function WriteStuff(ByVal msg As String) As Object
    Console.WriteLine(msg)
    Return Nothing
End Function

Based on your code, I assume you were following the CodeProject article, Towards Cleaner Code, A C# Asynchronous Helper so I used the name and signature of the delegate from that in my example. If you are using another library, the name and signature of the delegate might be different.

UPDATE: VB.Net does not support closures (check out http://msmvps.com/blogs/bill/archive/2006/04/05/89370.aspx for more info) so you cannot, as far as I can tell, pass parameters to the method. The simplest way I can think of to do this is to create your own closure class and call it like this...

Module Module1
    Sub Main()
        Dim c1 = New MyClosure("Hello World")
        Dim c2 = New MyClosure("Test 123")
        CodeToast.Async.Do(New Dlg(AddressOf c1.WriteStuff))
        CodeToast.Async.Do(New Dlg(AddressOf c2.WriteStuff))
        Console.ReadKey()
    End Sub
End Module
Public Class MyClosure
    Public Sub New(ByVal msg As String)
        Message = msg
    End Sub
    Public Message As String
    Public Sub WriteStuff()
        Console.WriteLine(Message)
    End Sub
End Class


Finally got around to solving this, in the 'more than one line' it is in C#...

I declared my delegate at the class level:

Public Delegate Sub loggerDelegate(ByVal a As LogEntry)

Then, inside my method, I make the async logging call

    ' make the async logging call
    Dim myDel As loggerDelegate = New loggerDelegate(AddressOf Logger.Write)
    myDel(logEntry)

I guess I should have called this, Asynchronous Logging with MS Enterprise Library without using MSMQ, but you get the drift.

Hope this helps someone else.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜