Reputation: 783
I need to implement a function that generates arrays of an unique combination number? This function will be accessible by a lot of devices (by using threads), and each device should get an unique address id (array of sbyte).
I previously used a function in C# to generate an unique number but I don't know how to implement this new case in VB.net.
public class GetUniqueNumber
{
static private int id = 0;
static private final Object lock = new Object();
public int getId()
{
synchronized (lock)
{
int temp = id;
id++;
return temp;
}
}
}
Upvotes: 0
Views: 844
Reputation: 11773
As integer
Public Class GetUniqueNumber
Private Shared id As Integer = 0
Private Shared lock As New Object
Public ReadOnly Property getID() As Integer
Get
Dim temp As Integer
SyncLock lock
temp = id
id += 1
End SyncLock
Return temp
End Get
End Property
End Class
as byte array
Public Class GetUniqueNumber
Private Shared id As Integer = 0
Private Shared lock As New Object
Public ReadOnly Property getID() As Byte()
Get
Dim temp As Byte()
SyncLock lock
temp = BitConverter.GetBytes(id)
id += 1
End SyncLock
Return temp
End Get
End Property
End Class
as byte array from int16
Public Class GetUniqueNumber
Private Shared id As Int16 = 0
Private Shared lock As New Object
Public ReadOnly Property getID() As Byte()
Get
Dim temp As Byte()
SyncLock lock
temp = BitConverter.GetBytes(id)
id += 1S
End SyncLock
Return temp
End Get
End Property
End Class
using biginteger
Public Class GetUniqueNumber
Private Shared id As BigInteger = 0
Private Shared lock As New Object
Public ReadOnly Property getID() As Byte()
Get
Dim temp As Byte()
SyncLock lock
temp = id.ToByteArray
id += 1
End SyncLock
If temp.Length <> 16 Then
Array.Resize(temp, 16)
End If
Return temp
End Get
End Property
End Class
or
Public Class GetUniqueNumber
Private Shared idLS As Long = 0L
Private Shared idMS As Long = 0L
Private Shared lock As New Object
Public ReadOnly Property getID() As Byte()
Get
Dim tempLS() As Byte
Dim tempMS() As Byte
Dim rv(15) As Byte
SyncLock lock
tempLS = BitConverter.GetBytes(idLS)
tempMS = BitConverter.GetBytes(idMS)
If idLS = Long.MaxValue Then
idMS += 1L
idLS = 0L
Else
idLS += 1L
End If
Array.Reverse(tempLS)
Array.Reverse(tempMS)
Array.Copy(tempLS, 0, rv, 8, tempLS.Length)
Array.Copy(tempMS, 0, rv, 0, tempMS.Length)
End SyncLock
Return rv
End Get
End Property
End Class
Upvotes: 1
Reputation: 34846
You need to use a SyncLock
, like this:
Public Class GetUniqueNumber
Private Shared id As Integer = 0
Private Shared lock = New Object()
Public Function getId() As Integer
SyncLock lock
Dim temp As Integer = id
id += 1
Return temp
End SyncLock
End Function
End Class
Upvotes: 1
Reputation: 18746
like this ?
' Define other methods and classes here
public class GetUniqueNumber
shared id as integer=0
shared readonly lock =new Object()
public function getId() as integer
SyncLock lock
dim temp =id
id=id+1
return temp
end synclock
end function
end class
Upvotes: 0