Link to home
Start Free TrialLog in
Avatar of mcainc
mcainc

asked on

VB.NET best way to check if index is out of bounds in array

Is there an easy way to check if an index is out of bounds when using arrays so that I can avoid the first chance exception?
Avatar of mcainc
mcainc

ASKER

I should clarify, I'm having a strange issue with this piece of a function that uses an array of a custom structure:

For x = 1 To UBound(PrivateMessageQ)
  PMQt = PrivateMessageQ(x)
  ...
Next

I'm getting the first chance exception in the line: PMQt = PrivateMessageQ(x)

This function is in a shared module & is being called by other threads... I believe that something is happening simultaneously & changing the array size before the loop has completed.

Does this sound right? Is there a way to lock functions like this until they are completed so I can avoid this?
Avatar of mcainc

ASKER

Oops, the function is in a Class that is used multiple times however the "PrivateMessageQ" array is a public array...

Avatar of Mike Tomlinson
"Is there a way to lock functions like this until they are completed so I can avoid this?"

Use SyncLock...you need an Object that all threads can access:

    Public Class Sync
        Public Shared SyncObject As New Object
    End Class

Then you utitlize it like this:

    SyncLock Sync.SyncObject
        For x = 1 To UBound(PrivateMessageQ)
            PMQt = PrivateMessageQ(x)
            ...
        Next
    End SyncLock

Avatar of mcainc

ASKER

ahhhh ok that makes sense, what about if i have some type of Try Catch exception or Exit Sub / Exit Function in the code...

Do I need to call End SyncLock in this event as well?

Example:

Public Sub Something()
    SyncLock Sync.SyncObject

    Try
            For x = 1 To UBound(PrivateMessageQ)
                PMQt = PrivateMessageQ(x)
                ...
            Next
    Catch
           Debug.Writeline("error")
           End SyncLock
    End Try

    End SyncLock
End Sub

or

Public Sub Something()
    SyncLock Sync.SyncObject

            For x = 1 To UBound(PrivateMessageQ)
                PMQt = PrivateMessageQ(x)

                If a = b Then
                    End SyncLock
                    Exit Sub
                End If
            Next

    End SyncLock
End Sub

ASKER CERTIFIED SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of mcainc

ASKER

yeah, it looks like i can't

thanks for the help, its working smoothly so far!