简体   繁体   English

c#引用其他类的静态属性时的线程安全性

[英]c# thread safety when referencing static properties on other classes

I have a method to generate fully qualified URLs that I wrote which I would like to have as static so its easy to call from models as needed. 我有一种方法来生成我写的完全限定的URL,我希望它具有静态,因此可以根据需要轻松地从模型中调用。

I'm still having problems however with being able to decide if its thread safe or not. 我仍然遇到问题,但是能否决定它的线程是否安全。

Here is the code. 这是代码。

    public string GenerateURLFromModel(string action, string controller)
    {
        HttpContextWrapper wrapper = new HttpContextWrapper(HttpContext.Current);
        Uri url = HttpContext.Current.Request.Url;
        UrlHelper urlHelper = new UrlHelper(new RequestContext(wrapper, RouteTable.Routes.GetRouteData(wrapper)));

        return url.AbsoluteUri.Replace(url.PathAndQuery, urlHelper.Action(action, controller));
    }

What I know already is: 我所知道的是:

1) The two strings passed in will be thread safe since they are immutable reference types. 1)传入的两个字符串将是线程安全的,因为它们是不可变的引用类型。

2) All objects instantiated within a static method can be considered thread safe since they exist only on the stack for that specific thread. 2)在静态方法中实例化的所有对象都可以被认为是线程安全的,因为它们仅存在于该特定线程的堆栈中。

What I'm unsure of is: 我不确定的是:

1) How does the use of HttpContext.Current and RouteTable.Routes play in this method? 1)如何在此方法中使用HttpContext.Current和RouteTable.Routes? They are both static properties that I'm passing into the constructors. 它们都是我传递给构造函数的静态属性。

My questions are: 我的问题是:

1) What are the implications of using these static properties? 1)使用这些静态属性有什么含义?

2) Does the rest of my understanding of the safeness of this method ring true? 2)我对这种方法的安全性的其余理解是否正确?

3) What rules can I keep in mind in the future to help determine thread safeness in situations like this? 3)将来我可以记住哪些规则来帮助确定这种情况下的线程安全性?

As long as you are not modifying shared state, or accessing state that is likely to be modified by other threads then you're fine. 只要您不修改共享状态,或访问可能被其他线程修改的状态,那么您就可以了。

In this case HttpContext.Current is local to the current thread anyway, so that isn't a problem; 在这种情况下,HttpContext.Current无论如何都是当前线程的本地,所以这不是问题; and RouteTable.Routes should only be modified in the startup event of your application, so that, too, should be OK. 和RouteTable.Routes只应在应用程序的启动事件中修改,因此也应该没问题。

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

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