none
Is BOOLEAN Thread Save in VB.NET? RRS feed

  • Question

  • Is a boolean variable inherently thread safe in Visual Basic (VS 2013)?

    For example, is this code thread safe:

    Dim processing as Boolean = false
    
    Private Sub DoStuff()
    
        If (processing) Then
            Exit Sub
        End If
    
        processing = True
    
        ... do what ever needs doing ...
    
        processing = False
    
    End Sub

    Monday, January 7, 2019 3:17 PM

All replies

  • See docs remarks as per below.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Monday, January 7, 2019 3:34 PM
    Moderator
  • Thank you for the quick reply Karen.

    You taught me something today.  As a transplanted C++/Java programmer, I did not know that the basic data types were structures.  I mistakenly thought they were primitive types.

    Based on this new info, I guess my code would need to be changed to:

    Dim processing as Boolean = false
    
    Private Sub DoStuff()
    
        SyncLock ME
            If (processing) Then
                Exit Sub
            End If
    
            processing = True
        End SyncLock
    
        ... do what ever needs doing ...
    
    
        SyncLock ME
            processing = False
        End SyncLock
    
    End Sub

    Monday, January 7, 2019 4:29 PM
  • Yes, this would be the correct logic working in threads.

    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Monday, January 7, 2019 4:53 PM
    Moderator