VBobCat
VBobCat

Reputation: 2712

How to write thread-safe methods?

Is this good practice and enough to ensure thread-safety to the method DoSomething in VB.NET?

Public Class MyForm : Inherits Form

    Public Sub DoSomething(parameter As Object)
        If Me.InvokeRequired Then
            Me.Invoke(Sub() DoSomething(parameter))
        Else
            'Do Something
        End If
    End Sub

End Class

Upvotes: 1

Views: 446

Answers (1)

Steven Doggart
Steven Doggart

Reputation: 43743

I believe you may mean something different by thread-safety than the usual definition of the term. The normal meaning of the term is that the same method or object may be called by multiple threads simultaneously without errors or negative side effects. Typically, that kind of thread-safety is accomplished via statelessness and locking (e.g. SyncLock).

However, in your example, the code is not attempting to provide that kind of thread-safety, or at least not directly. It does accomplish that kind of thread-safety, but only by forcing all invocations to be executed on the same single thread (the UI thread). WinForm applications (which I presume this is) require that all UI work is done on the UI thread. Therefore, if a method which does something with the UI is called from another thread, it must first invoke back to the UI thread before completing its work. For that specific scenario, the code you have posted is fine.

Upvotes: 3

Related Questions