3

Keeping these in mind

-HttpContext.Current

-Foreach

I'm having trouble wrapping my head around this... Is this code "thread safe" in ASP.NET?

public static bool IsCookieMissing()
{
    foreach (string cookieKey in HttpContext.Current.Request.Cookies.AllKeys)
    {
        if (cookieKey.EndsWith("cookie_name"))
        {
            return false;
        }
    }
    return true;
}
Community
  • 1
  • 1
felickz
  • 4,292
  • 3
  • 33
  • 37

2 Answers2

4

Technically, yes, this code is thread-safe.

HttpContext.Current returns the context associated with the current request. Although IIS might use several threads to handle a given request (thread agility), it will not run these threads in parallel (it will only switch threads during asynchronous I/O).

Therefore, no more than one thread will access HttpContext.Current.Request.Cookies at the same time, and you don't need locking here.

Scorpion
  • 784
  • 7
  • 25
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
2

Is this code "thread safe" in ASP.NET?

That depends on what you expect it to do. It most likely does what you expect to do, so it is "thread safe", unless you are starting your own threads that are calling it. HttpContext.Current is the Current HttpContext at which time it was called. Your concern about the issues in this question that you linked to aren't needed - you aren't using any closures.

Community
  • 1
  • 1
vcsjones
  • 138,677
  • 31
  • 291
  • 286
  • good point about starting your own threads. My code does implement that pattern to do various utility tasks within ASP.NET. – felickz Jul 11 '12 at 13:16