felickz
felickz

Reputation: 4461

Is using foreach over an HttpContext.Current inside a static method thread safe?

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;
}

Upvotes: 3

Views: 589

Answers (2)

Frédéric Hamidi
Frédéric Hamidi

Reputation: 263147

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.

Upvotes: 4

vcsjones
vcsjones

Reputation: 141703

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.

Upvotes: 2

Related Questions