Is this code thread safe?
- by Shawn Simon
''' <summary>
''' Returns true if a submission by the same IP address has not been submitted in the past n minutes.
''' </summary>
Protected Function EnforceMinTimeBetweenSubmissions() As Boolean
Dim minTimeBetweenRequestsMinutes As Integer = 0
Dim configuredTime = ConfigurationManager.AppSettings("MinTimeBetweenSchedulingRequestsMinutes")
If String.IsNullOrEmpty(configuredTime) Then Return True
If (Not Integer.TryParse(configuredTime, minTimeBetweenRequestsMinutes)) _
OrElse minTimeBetweenRequestsMinutes > 1440 _
OrElse minTimeBetweenRequestsMinutes < 0 Then
Throw New ApplicationException("Invalid configuration setting for AppSetting 'MinTimeBetweenSchedulingRequestsMinutes'")
End If
If minTimeBetweenRequestsMinutes = 0 Then
Return True
End If
If Cache("submitted-requests") Is Nothing Then
Cache("submitted-requests") = New Dictionary(Of String, Date)
End If
' Remove old requests.
Dim submittedRequests As Dictionary(Of String, Date) = CType(Cache("submitted-requests"), Dictionary(Of String, Date))
Dim itemsToRemove = submittedRequests.Where(Function(s) s.Value < Now).Select(Function(s) s.Key).ToList
For Each key As String In itemsToRemove
submittedRequests.Remove(key)
Next
If submittedRequests.ContainsKey(Request.UserHostAddress) Then
' User has submitted a request in the past n minutes.
Return False
Else
submittedRequests.Add(Request.UserHostAddress, Now.AddMinutes(minTimeBetweenRequestsMinutes))
End If
Return True
End Function