Question

Say I've got the following sub that simply adds passed items to a ListView control:

Private Sub AddListItem(ByVal item As ListViewItem)
    UIList.Items.Add(item)
End Sub

And I use that from a BackgroundWorker thread, like so:

UIList.BeginInvoke(Sub() AddListItem(lvItem))

Well quite by accident I've just discovered that it doesn't seem to matter which control is used to call the Invoke\BeginInvoke method, or even if I omit a control altogether and just call the method directly – which I assume just uses Me.<Method> behind the scenes – it doesn't seem to matter. The code still works.

So, is using the affected control to call the method just a way to make following the code easier? What, if any, are the other advantages? And are there certain pitfalls one needs to be aware of when using a different control?

Was it helpful?

Solution

Using ILSpy and digging down the Control.Invoke method, an excerpt is

...
UnsafeNativeMethods.PostMessage(
    new HandleRef(this, this.Handle), 
    Control.threadCallbackMessage, 
    IntPtr.Zero, 
    IntPtr.Zero);
 ...

In addition, MSDN states:

The Invoke method searches up the control's parent chain until it finds a control or form that has a window handle if the current control's underlying window handle does not exist yet. If no appropriate handle can be found, the Invoke method will throw an exception. Exceptions that are raised during the call will be propagated back to the caller.

So usually it shouldn't matter which control you post to.

Personally, I use the "nearest" control I can get to call the Invoke method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top