質問

Let's say I call the following method when a user logs into my mvc application:

public static bool IsValidBrowser()
{
    var browser = HttpContext.Current.Request.Browser;

    if (browser.Browser == "IE") {
        if (browser.MajorVersion < 10) {
            return false;
        }
    }
    return true;
}

Is this method thread safe? Obviously I'm not modifying anything here, but might it be possible that HttpContext.Current changes in the middle of this method?

Would writing the code this way make it thread safe?

public ActionResult Login () 
{
    bool validBrowser = IsValidBrowser(HttpContext.Current.Request.Browser);
}

public static bool IsValidBrowser(HttpBrowserCapabilities browser)
{
    if (browser.Browser == "IE") {
        if (browser.MajorVersion < 10) {
            return false;
        }
    }
    return true;
}
役に立ちましたか?

解決

HttpContext.Current itself is a static method and it'll return the context from the current thread so you have nothing to worry about.

他のヒント

Is this method thread safe?

Yes this method is thread safe as @DoctorMick already explained. Adding one more point.

Microsoft’s Framework Class Library (FCL) guarantees that all static methods are thread safe. The FCL had to do this internally because there is no way that multiple companies producing different assemblies could coordinate on a single lock for arbitrating access to the resource.

So if you are using FCL static method you don't need to think about thread safety. eg(Console Class, Math class etc.)

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top