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?
ASKER
Oops, the function is in a Class that is used multiple times however the "PrivateMessageQ" array is a public array...
"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
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
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
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
yeah, it looks like i can't
thanks for the help, its working smoothly so far!
thanks for the help, its working smoothly so far!
ASKER
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?