这个静态类会在多用户场景中中断吗?

发布于 2024-10-09 16:38:46 字数 501 浏览 0 评论 0 原文

假设我使用扩展方法创建了一个如下所示的静态类:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

累赘 2024-10-16 16:38:46

您的字典只有三种情况可用:要么必须共享,要么不得共享,或者您不知道或不关心嗯>。

如果它必须被共享,你就必须实现适当的锁定。但由于您在 ToOutput() 中要做的第一件事就是清除字典,因此共享它似乎不会给您带来很多好处。

因此,我们只剩下两种情况(不得共享,或者不知道或不关心),在这两种情况下,最好将其隔离ToOutput() 内局部变量中的字典:

public static OutputClass ToOutput(this InputClass input)
{
    Dictionary<int, SomeClass> algoMgmtDict = new Dictionary<int, SomeClass>();
    // Dictionary starts up empty, no need to clear anything.

    // Do some kind of transform over the `input` object.
    // Return an OutputClass instance.
}

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():

public static OutputClass ToOutput(this InputClass input)
{
    Dictionary<int, SomeClass> algoMgmtDict = new Dictionary<int, SomeClass>();
    // Dictionary starts up empty, no need to clear anything.

    // Do some kind of transform over the `input` object.
    // Return an OutputClass instance.
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文