简体   繁体   English

静态方法线程安全

[英]Static method thread safety

Let's say I call the following method when a user logs into my mvc application: 假设当用户登录我的mvc应用程序时,我调用以下方法:

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? 显然我没有在这里进行任何修改,但是HttpContext.Current是否有可能在此方法的中间进行更改?

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本身是一个静态方法,它将从当前线程返回上下文,因此您无需担心。

Is this method thread safe? 此方法线程安全吗?

Yes this method is thread safe as @DoctorMick already explained. 是的,此方法是线程安全的,如@DoctorMick所述。 Adding one more point. 再增加一点。

Microsoft's Framework Class Library (FCL) guarantees that all static methods are thread safe. Microsoft的框架类库(FCL)保证所有静态方法都是线程安全的。 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. FCL必须在内部执行此操作,因为无法生产多个不同程序集的多个公司可以在单个锁上进行协调以仲裁对资源的访问。

So if you are using FCL static method you don't need to think about thread safety. 因此,如果您使用的是FCL静态方法,则无需考虑线程安全性。 eg(Console Class, Math class etc.) 例如(控制台类,数学类等)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM