Share via

Delegate use needed?

Peter Volz 1,295 Reputation points
2024-02-20T10:41:49.92+00:00

Hello,

When I'm making and running some code in a new thread, I use similar subs like this to work with controls:

    Private Sub SetFocus()
        If Button1.InvokeRequired Then
            Invoke(Sub() Button1.Focus())
        Else
            Button1.Focus()
        End If
    End Sub

However, in some sample codes I've found this with one extra line at the beginning:

    Delegate Sub SetFocusCallback()
    Private Sub SetFocus()
        If Button1.InvokeRequired Then
            Invoke(Sub() Button1.Focus())
        Else
            Button1.Focus()
        End If
    End Sub

Although reading Delegate Statement on msdn didn't make it very clear for me, but for is it needed or recommended to also have the first Delegate line when just working with controls inside threads? Thanks :)

Developer technologies | VB
Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.


Answer accepted by question author

Bruce (SqlWork.com) 84,086 Reputation points
2024-02-21T16:23:50.2766667+00:00

The second sample doesn’t use the delegate, so it’s unnecessary. Delegate allow defining a variable that contains a callback(s). A common case the click event, where you set the click delegate to the callback method.

in your 2nd sample it’s always calling Button1.Focus, but if you wanted the routine to call a settable value it could use the delegate.

Was this answer helpful?

1 person found this answer helpful.
0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Dewayne Basnett 1,386 Reputation points
    2024-02-21T20:28:42.6033333+00:00

    I have seen this coded this way too,

        Private Sub SetFocus()
            If Me.InvokeRequired Then
                Me.Invoke(Sub() SetFocus())
            Else
                Button1.Focus()
            End If
        End Sub
    

    Was this answer helpful?

    0 comments No comments

  2. Jiachen Li-MSFT 34,241 Reputation points Microsoft External Staff
    2024-02-21T08:38:10.72+00:00

    Hi @Peter Volz .

    If SetFocus() is only called within the same context where it's defined and always called from the UI thread, then you may not need to define it as a delegate.

    Best Regards.

    Jiachen Li


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.