简体   繁体   English

管理静态属性的最佳方法

[英]Best way to manage a static property

I have this code: 我有以下代码:

public static class ProcessClass()
{
     public static string MyProp {get;set;}

     public static void ProcessMethod(InputObject input)
     {
         if(String.IsNullOrEmpty(MyProp)
              MyProp = input.Name();

         //do stuff

         MyProp = null;

     }   

 }

Now, everything except for MyProp was already in place. 现在,除MyProp之外的所有内容MyProp就绪。 I needed a way to track the original input.Name throughout the code since it can change and also because ProcessMethod could get called again internally with a different input.Name value due to business rules, and I need to state that this second calling came from input.Name . 我需要一种方法来跟踪整个代码中的原始input.Name ,因为它可以更改,并且还因为ProcessMethod可以在内部使用不同的input.Name值再次被调用,这是由于业务规则所致,我需要声明第二个调用来自input.Name

Obviously, this is bad since if two people do this at the same time, they will both share the same MyProp value, and simply making is null at the end seems dangerous and hacky. 显然,这是不好的,因为如果两个人同时执行此操作,他们将共享相同的MyProp值,并且最后简单地使null为空似乎是危险和棘手的。 I don't really have the option of changing this method to be non static because that would involve changing A LOT of the codebase, which isn't really an option. 我实际上没有将这种方法更改为非静态的选择,因为这将涉及更改很多代码库,这实际上不是一个选择。

What are ways around using a static property, but still being able to keep my original input.Name value without risking thread safety issues? 有什么方法可以使用静态属性,但是仍然可以保留我的原始input.Name值而不会冒线程安全问题的风险? One option I am thinking is is to have every method accept an input.Name() and track is that way(and remove the MyProp ), but I can picture that getting out of hand fast, and extremely messy. 我在想的一个选择是让每个方法都接受一个input.Name()和track就是这种方式(并删除MyProp ),但是我MyProp它很快就失控了,而且非常混乱。

I don't need to have this be a property, but if it is it obviously needs to be static in this class. 我不需要将其作为属性,但是如果是,则显然在此类中它必须是静态的。

由于它可能是多用户环境,因此将字符串替换为ConcurrentDictionary ,在其中将input.Name()存储为Value并将用户的唯一标识符(id,名称等)存储为Key

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

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