Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it thread-safe to write this?

Tags:

asp.net

Can I write something like the following (in an assembly being used in an ASP.NET web page)?

public static string CurrentAuthenticatedUserFromHttpRequest
{
    get
    {
        if (HttpContext.Current.Items["AuthUser"] == null)
        {
            return string.Empty;
        }

        return HttpContext.Current.Items["AuthUser"].ToString(); //set in "TryAuthenticate"
    }
}

It is going to be a static read-only property. The value (to HttpContext.Current.Items["AuthUser"]) is set through a httphandler.

Just wondering on how this would perform during multiple requests. Is the data going to be accurate when multiple users try to access the same property (in multiple requests), even when high volumes of requests come in?

like image 973
user203687 Avatar asked Mar 17 '26 01:03

user203687


1 Answers

Yes, this is threadsafe. The static HttpContext.Current property differs per thread and contains the context for the request that the thread is currently handling.

like image 70
flup Avatar answered Mar 18 '26 18:03

flup