2

Im having a problem understanding if accessing httpcontext inside a shared function, without passing in the httpcontext as a parameter is thread safe?

My questions is: Are the 2 functions in the util class equally thread safe?

Class foo
    Sub main()
       Dim qs1 = util.getQS(HttpContext.Current)
       Dim qs2 = util.getQS()
    End Sub
End Class

Class util
    Shared Function getQS(hc As HttpContext) As String
        Return hc.Request.QueryString.ToString
    End Function
    Shared Function getQS() As String
        Return HttpContext.Current.Request.QueryString.ToString
    End Function
End Class


EDIT
I found a SO post that i missed in my initial research, which also have some good answers.
For the interested: HttpContext.Current.Response inside a static method

Community
  • 1
  • 1
KorsG
  • 729
  • 1
  • 7
  • 16

2 Answers2

3

The two functions in the question are equivalent in terms of thread safety.

Although HttpContext is not thread safe, getting a reference to HttpContext.Current is thread safe. Normally the lack of thread safety on the per-request HttpContext object is not an issue, because only one thread at a time processes a given request.

However, it can become an issue if you have background worker threads, etc, that are referencing the HttpContext.Current.

RickNZ
  • 18,448
  • 3
  • 51
  • 66
  • Thanks @RickNZ - where could these background worker threads originate from? IIS ? – KorsG Jan 06 '12 at 17:09
  • 1
    If you store `HttpContext` into a static variable, then it can become visible to IIS threads (not good). Background threads are ones that you create directly with `new Thread()` or use indirectly via a ThreadPool of some kind. – RickNZ Jan 06 '12 at 23:43
0

The short answer is no. See this question and its answers for more detail: Using an HTTPContext across threads

Community
  • 1
  • 1
competent_tech
  • 44,465
  • 11
  • 90
  • 113