Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 458
felickz Avatar asked Apr 21 '26 14:04

felickz


2 Answers

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.

like image 193
Frédéric Hamidi Avatar answered Apr 24 '26 04:04

Frédéric Hamidi


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.

like image 26
vcsjones Avatar answered Apr 24 '26 04:04

vcsjones



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!