4

In C# you use BeginInvoke like this:

obj.BeginInvoke((Action)(() =>
{
    //do something
}));

I tried to translate it to VB.NET, and ended up with this code, that seems to work:

obj.BeginInvoke(
    Sub()
        'do something'
    End Sub
)

The snippets look very different to me, especially because the (Action) (() => part is missing completely. Is this the correct way to use BeginInvoke in VB.NET?


this is not a duplicate of How to use BeginInvoke C# because the question and every answer uses C# (if any programming language is used). C#-code doesn't help much when you are unsure about if you used the correct VB.NET syntax.

Community
  • 1
  • 1
Breeze
  • 2,010
  • 2
  • 32
  • 43
  • 2
    Looks fine to me. Lambdas and Anonymous methods are one of the things that look VERY different between C# and VB.NET. – Bradley Uffner May 17 '16 at 14:29
  • Possible duplicate of [How to use BeginInvoke C#](http://stackoverflow.com/questions/14388136/how-to-use-begininvoke-c-sharp) – Matt Wilko May 17 '16 at 15:09
  • 1
    @Matt why should this be a duplicate if this question is about VB.NET syntax and the duplicate target uses C#? – Breeze May 17 '16 at 15:32
  • *Possible* duplicate - it explains exactly what Action is and why it is there – Matt Wilko May 17 '16 at 16:03

2 Answers2

2

(Action) just casts the lambda to an Action, which isn't needed in VB.NET. The Sub() lambda is all you need.

You have got the correct conversion.

Although note that BeginInvoke() must be followed by EndInvoke(), otherwise you will get thread leaks.

Visual Vincent
  • 18,045
  • 5
  • 28
  • 75
1

Yes, the (Action) (() => doesn't return anything so Sub in VB.Net is equivalent. It'd be a Func in C# if it did return something.

Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321