"what is the best practice for thread-safe access to controls" Code Answer


in my opinion performing invocation (like you do) is the best practice. i don't think there is a general best practice, but the control.invoke() and control.begininvoke() methods are used by many.

accessing controls in a thread-safe manner takes longer to code than seems necessary because i have to repeat functions like the following over and over

i could end up writing one for every method and property of every control.

not necessarily, you can still simplify your code in a few different ways. for instance, a trackbar derives from system.windows.forms.control which means it may be casted into the control class, thus you can generalize the functions:

private sub setenabled(ctrl as control, value as integer)
    if ctrl.invokerequired then
        ctrl.invoke(sub() ctrl.enabled = value)
        ctrl.enabled = value
    end if
end sub

but there's actually an even simpler way to do it: via extension methods. you can create an extension method that will automatically perform the invocation and the invokerequired check for you.

thanks to that a sub()-lambda expression can be casted/converted into a delegate, you can use it as an argument for your method and call it at will:

imports system.runtime.compilerservices

public module extensions
    <extension()> _
    public sub invokeifrequired(byval control as control, byval method as [delegate], byval paramarray parameters as object())
        if parameters isnot nothing andalso _
            parameters.length = 0 then parameters = nothing 'if parameters has a length of zero then no parameters should be passed.
        if control.invokerequired = true then
            control.invoke(method, parameters)
        end if
    end sub
end module

with this extension method, which you can call on any class that derives from system.windows.forms.control, you will now be able to call for example:

me.invokeifrequired(sub() trackbar1.enabled = true)
'me is the current form. i prefer to let the form do the invocation.

by having this you may also invoke longer statements:

                        button1.enabled = false
                        label1.text = "something happened..."
                        progressbar1.value += 5
                    end sub)
By Pulkit Sethi on October 1 2022

Answers related to “what is the best practice for thread-safe access to controls”

Only authorized users can answer the Search term. Please sign in first, or register a free account.