简体   繁体   中英

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.

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));
    }

1) The two strings passed in will be thread safe since they are immutable reference types.

2) All objects instantiated within a static method can be considered thread safe since they exist only on the stack for that specific thread.

1) How does the use of HttpContext.Current and RouteTable.Routes play in this method? They are both static properties that I'm passing into the constructors.

1) What are the implications of using these static properties?

2) Does the rest of my understanding of the safeness of this method ring true?

3) What rules can I keep in mind in the future to help determine thread safeness in situations like this?

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; and RouteTable.Routes should only be modified in the startup event of your application, so that, too, should be OK.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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