I have an application that runs several asynchronous methods to create messages that are sent with a unique id to a remote host.
Two types of messages are being created in two separate classes. One class is inherited from the other but the shared methods are shadowed meaning they are different.
I would like the ID to be an incremented integer.
Does anyone have a good way of accomplishing this task? I have looked up the use of static numbers and class generated ids but they don't cover the shared method issue.
I am also aware of a single shared method being able to use a static number but that doesn't help when my method is shadowed.
You'll need some single-instance way of doing this. VB.NET natural way would be using Module:
Module IDHelper
Private fLastID As Integer
Public Function NextMessageID() As Integer
Return Threading.Interlocked.Increment(fLastID)
End Function
End Module
Nice way of doing this is using singleton. Or somehing like that. But your original idea with shared member works as well. Problem could be in missing synchronization.
Public Class Base
Private Shared fLastID As Integer
Protected Function NextMessageID() As Integer
Return Threading.Interlocked.Increment(fLastID)
End Function
Public Function CreateMessage() As String
Return "Base message is " & NextMessageID()
End Function
End Class
Public Class Inherited
Inherits Base
Public Shadows Function CreateMessage() As String
Return "Inherited message is " & NextMessageID()
End Function
End Class
Shadowing functions is almost never a good idea. Overriding is the good way to go.