This repository has been archived by the owner on Aug 4, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ThreadSafeRandom.vb
55 lines (47 loc) · 1.67 KB
/
ThreadSafeRandom.vb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
''' <summary>
''' A thread-safe random number class.
''' </summary>
Public Class ThreadSafeRandom ' Thanks to nitro#0001 (233648473390448641) for the snippet this is all based off of.
Private Shared ReadOnly _global As Random = New Random()
<ThreadStatic> Private Shared _local As Random
Private Shared Property LocalRandom As Random
Get
If _local Is Nothing Then
SyncLock _global
If _local Is Nothing Then _local = New Random(_global.Next())
End SyncLock
End If
Return _local
End Get
Set(value As Random)
_local = value
End Set
End Property
''' <summary>
''' Returns a random number that is less than the specified maximum.
''' </summary>
Public Function NextNumber(max As Integer) As Integer
Return LocalRandom.Next(max)
End Function
''' <summary>
''' Returns a random number within a specified range.
''' </summary>
Public Function NextNumber(min As Integer, max As Integer) As Integer
Return LocalRandom.Next(min, max + 1)
End Function
''' <summary>
''' Returns a number between 0.0 and 1.0.
''' </summary>
Public Function NextDouble() As Double
Return LocalRandom.NextDouble
End Function
''' <summary>
''' Returns whether the specified probability was hit.
''' </summary>
Public Function ProbabilityCheck(probability As Double) As Boolean
If probability >= 1.0 Then Return True
If probability <= 0.0 Then probability = 0.01
Dim result = LocalRandom.NextDouble
Return result <= probability
End Function
End Class