引用其他类的静态属性时,C#线程安全 [英] c# thread safety when referencing static properties on other classes

查看:233
本文介绍了引用其他类的静态属性时,C#线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法来生成完全限定的网址,我写的,我想有作为静态的,所以它很容易根据需要从模型调用。

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.

下面是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),因为它们是不可变的引用类型传递的两个字符串将是线程安全的。

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

2)的静态方法中实例化的所有对象都可以,因为它们只存在堆栈特定线程上被认为是线程安全的。

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)如何使用HttpContext.Current和RouteTable.Routes在这种方法玩?他们是我突入构造静态属性。

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)什么是使用这些静态属性的含义是什么?

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

2)是否我的这种方法环真safeness?

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

3)我什么规则可以记住的未来,以帮助确定在这样的情况下线程safeness?

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.

在这种情况下,HttpContext.Current是本地到当前线程无论如何,所以这不是一个问题;和RouteTable.Routes应该只在您的应用程序的启动事件进行修改,这样一来,也应该没问题。

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.

这篇关于引用其他类的静态属性时,C#线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆