vb.net how to pass structure to thread by byref?

2020-05-03 11:54发布

问题:

I get a build error when I try to pass a structure reference into a thread.

dim antenna_frame_buffer as Antenna_Frame_Buffer_structure
...

new_buffer_write_thread = new Thread( AddressOf frame_buffer_write_Thread )
new_buffer_write_thread.Start( antenna_frame_buffer )   

...

    sub frame_buffer_write_Thread( ByRef antenna_frame_buffer as Antenna_Frame_Buffer_structure ) 
...

THE ERROR...

Severity Code Description Project File Line Suppression State Error BC30518 Overload resolution failed because no accessible 'New' can be called with these arguments: 'Public Overloads Sub New(start As ThreadStart)': Method 'Public Sub frame_buffer_write_Thread(ByRef antenna_frame_buffer As Embedded_Communication_Interface.Antenna_Frame_Buffer_structure)' does not have a signature compatible with delegate 'Delegate Sub ThreadStart()'. 'Public Overloads Sub New(start As ParameterizedThreadStart)': Method 'Public Sub frame_buffer_write_Thread(ByRef antenna_frame_buffer As Embedded_Communication_Interface.Antenna_Frame_Buffer_structure)' does not have a signature compatible with delegate 'Delegate Sub ParameterizedThreadStart(obj As Object)'. SYS HUB and HW GUI C:\PRIMARY\WORK\SYSTEM HUB\SOURCE\Embedded_Communication_Interface.vb 1030 Active

回答1:

You can't. You're not actually calling that method directly anyway, so how could the ByRef parameter be of use? You're calling the Thread.Start method and it doesn't have a ByRef parameter, so you couldn't get the value back that way. That's even ignoring the fact that Thread.Start returns immediately and you don't know when the method it invokes will return, so you couldn't know when the modified value was available anyway. In short, ByRef parameters don't make sense in such a context so don't try to use them.

EDIT:

You may be able to use a Lambda expression that calls your method as the delegate when you create the thread and then you will be able to get the code to run:

new_buffer_write_thread = New Thread(Sub() frame_buffer_write_Thread(antenna_frame_buffer))
new_buffer_write_thread.Start()

I don't think that that will ever return the parameter value after the method completes to the original variable though and, if it did, you'd not know when it did so because you don't know when the method completed, which is exactly why it shouldn't happen at all. I think that LINQ creates a closure that shields the original variable from changes via that parameter, even though it appears like they'd be linked.



回答2:

Structure cannot be passed by reference to a thread. However, and fortunately, an object of a class CAN be passed by reference.



标签: vb.net