Is this code thread safe?

Posted by Shawn Simon on Stack Overflow See other posts from Stack Overflow or by Shawn Simon
Published on 2010-04-29T13:15:50Z Indexed on 2010/04/29 13:17 UTC
Read the original article Hit count: 356

Filed under:
|
''' <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

© Stack Overflow or respective owner

Related posts about vb.net

Related posts about ASP.NET