这个静态类会在多用户场景中中断吗?
假设我使用扩展方法创建了一个如下所示的静态类:
public static class MyStaticExtensionClass
{
private static readonly Dictionary<int, SomeClass> AlgoMgmtDict
= new Dictionary<int, SomeClass>();
public static OutputClass ToOutput(this InputClass input)
{
// clears up the dict
// does some kind of transform over the input class
// return an OutputClass object
}
}
在多用户系统中,状态管理字典是否无法为转换算法提供正确的值?常规类是更好的设计还是将字典推入方法中是更好的设计?
Say I make a static class like following with an extension method:
public static class MyStaticExtensionClass
{
private static readonly Dictionary<int, SomeClass> AlgoMgmtDict
= new Dictionary<int, SomeClass>();
public static OutputClass ToOutput(this InputClass input)
{
// clears up the dict
// does some kind of transform over the input class
// return an OutputClass object
}
}
In a multi user system, will the state management dictionary fail to provide correct values for the transform algorithm? Will a regular class be a better design or shoving the Dictionary inside the method a better design?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的字典只有三种情况可用:要么必须共享,要么不得共享,或者您不知道或不关心嗯>。
如果它必须被共享,你就必须实现适当的锁定。但由于您在
ToOutput()
中要做的第一件事就是清除字典,因此共享它似乎不会给您带来很多好处。因此,我们只剩下两种情况(不得共享,或者不知道或不关心),在这两种情况下,最好将其隔离
ToOutput()
内局部变量中的字典:There are only three scenarios available for your dictionary: either it must be shared, or it must not be shared, or you don't know or care.
If it must be shared, you'll have to implement proper locking. But since the first thing you're doing in
ToOutput()
is to clear the dictionary, it doesn't look like sharing it will bring you many advantages.So, we're down to the two remaining scenarios (must not be shared, or don't know or care), and in both cases it would be better to isolate the dictionary in a local variable inside
ToOutput()
: