Sunday, July 28, 2013

.NET - Accessing Windows Forms Controls Across Threads

Windows Forms controls have the irksome property of being thread-unsafe.  Microsoft has an article on changing control properties across threads, but it is very complicated.  I believe I can do a better job of explaining how to do this.

First, you'll need a subroutine to actually interact with the control.  This subroutine will always execute on the form's thread.  Once you have that routine, declare a delegate that has the same arguments as the sub.  Perhaps an example would make this clearer:

Sub ProcessPacket(Packet As Packet6UserList)
 'code that accesses Windows Forms controls
End Sub
Delegate Sub ProcessPacketCallback(Packet As Packet6UserList)

On the non-GUI thread, create an instance of the delegate that points to your subroutine:

Dim ppc As New ProcessPacketCallback(AddressOf ProcessPacket)

Simply invoke that callback on the form to execute it in a thread-safe manner!  Parameters to the function are passed to Invoke after the delegate instance in an array.

Me.Invoke(ppc, {Packet})

No comments:

Post a Comment