使用 VB.Net“共享”时是否有任何性能或争用考虑因素?或 C#“静态”类和方法?
我在 WCF 服务后面有一个 C# 类库。该库包含声明为静态的 ClassA。这个静态类有一个方法 MethodA,它接受一个字符串并使用 LINQ 查询数据库以获取该字符串的翻译,然后通过 Web 服务将其发送回客户端。
我的问题是在这种情况下使用静态类和静态方法是否是糟糕的设计。类和方法是否应该是非静态的,以便每个客户端出于性能、争用或其他原因获得自己的类实例?谢谢。
I have a C# class library behind a WCF service. The library contains ClassA which is declared as static. This static class has a method MethodA which accepts a string and uses LINQ to query the database for a translation of the string which it then sends back through the webservice to the client.
My question is whether using a static class and static method in this situation is bad design. Should the class and method be non-static so that each client gets their own instance of the class for performance, contention, or other reasons? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我个人对静态方法和类比某些人更宽容,所以我想说这取决于情况。静态方法可重入和线程安全吗?那么也许就没事了。否则它可能会严重扩展。
我看到的一个问题是数据上下文。使用静态方法,您可能无法对数据库连接的生命周期进行细粒度的控制?另一种方法可能是使其成为非静态类和方法,并在 WCF 服务的静态构造函数中对其进行初始化。这样您以后可以根据需要更轻松地修改行为。
实际上,WCF 服务中的静态构造函数如果有任何失败的可能(例如数据库擅离职守),那就很糟糕。关键是它将允许对服务本身进行更细粒度的控制。
I'm personally more forgiving towards static methods and classes than some people might be, so I'd say it depends. Is the static method reentrant and thread safe? Then it might be okay. Otherwise it would probably scale badly.
One problem I see is the data context. With a static method, you probably don't have fine grained control over the life span of the database connection? An alternative might be to make it a non-static class and method, and initializing it in a static constructor of the WCF service. That way you can more easily modify the behavior later if need be.
Actually, static constructors in WCF services are bad, if they have any chance of failing, like the database being AWOL for a second. The point was that it would allow more fine grained control in the service itself.
我同意索拉林已经回答的内容。我通常认为静态类没有任何危害,尤其是。当它仅包含执行某些操作并返回结果而不触及任何静态字段或属性的静态方法时。然而,一旦其中任何一个发生修改,那就可能意味着麻烦。 (例如在 SO 上搜索有关单例和并发的任何讨论。)从
性能角度来看,理论上调用静态方法应该比调用非静态方法稍快(尽管出于所有实际目的,这可能永远不会) em> 产生任何显着差异),因为运行时不必传递
this
/Me
指针,并且因为使用静态方法,肯定不会产生任何开销来自虚拟方法调用。I agree with what Thorarin has already answered. I usually don't see any harm in static classes, esp. when it contains only static methods that do something and return a result without ever touching any static fields or properties. However, as soon as there are modifications of any of those, that could mean trouble. (Search e.g. for any discussion on Singletons and concurrency here on SO.)
Performance-wise, calling a static method should theoretically be slightly faster than calling a non-static method (although for all practical purposes this will probably never make any significant difference), since the runtime doesn't have to pass a
this
/Me
pointer and because with static methods, there'll definitely be no overhead resulting from virtual method calls.