BeginInvoke with / without using MethodInvoker - doesn't it matter?

I saw these 2 versions of the code, looking at the code of other developers:

one.

Me.BeginInvoke(New MethodInvoker(Sub() cbo.ShowPopup())) 

2.

  Me.BeginInvoke(Sub() cbo.ShowPopup() End Sub) 

Are both statements equivalent, or are they somewhat different? Also, EndInvoke () is not required for BeginInvoke ()?

+6
source share
1 answer

No, there is no functional difference between the two. There is only a very slight difference in implementation, nothing to worry about. Use the syntax you prefer for readability, most of them prefer fragment (2).

Some coefficients that fragment (1) was written by a C # programmer. BeginInvoke's first argument is System.Delegate , which is the base class of all delegate types. C # requires that you use a specific delegate type, because it is a very highly secure type. But VB.NET has a reputation for a (nearly) dynamic language and doesn't make the same demand, even with Option Strict On .

I recommend that you use the ildasm.exe utility to view the generated code for both operators. You will see that they create the same code. Just one very slight difference: the compiler uses a different type of delegate. Necessarily so, since he does not have special knowledge of MethodInvoker. This delegate type is automatically generated from the lambda expression and has the same name as VB$AnonymousDelegate_0 . This may cause the compiler to work just-in-time, assuming you use MethodInvoker sequentially and not use Ngen. It is very difficult to qualify and impossible to accurately measure. This is just a one-time cost, and nothing to worry about.

Another detail is the type security that C # requires. You can intentionally break code by using, say, Sub(arg As Integer) to express a lambda. This will cause the program to crash at runtime because the arg argument is not available. If you use MethodInvoker, you will get a compile time error. This is better than trying to debug a runtime error. But it is also likely that you will change the delegate type to Action(Of Integer) , and it will still crash.

And no, you do not need (and should not) call EndInvoke (). These methods do not have very good names, because they make them too much like delegate type methods. This is a bit of a design mistake. Find nitty-gritty in this answer .

+6
source

Source: https://habr.com/ru/post/1013718/


All Articles