c# - 静态函数需要锁定机制?

标签 c# multithreading

我创建了一个包含 5 个静态函数的 CommonUtils.cs 文件(这样我就可以为 Visual Studio 中的其他项目“复制”这个 .cs,因为我开发了不同的 C# 应用程序)以及许多源文件。

现在,我已将项目编译为 DLL。此 dll 作为应用程序通过 IIS 服务器托管。许多客户使用此 dll 来执行某些操作,例如生成报告。

我被告知“静态函数”在这种情况下不能大量使用,应该应用“锁定”机制,因为没有锁,单个程序实例的多个线程或程序的多个实例,两者都可能表现出意外。是真的吗?

最佳答案

I have been informed that "static functions" must not be used generously in this context and they should be applied, a "locking" mechanism since without lock, multiple threads of a single instance of program or multiple instances of a program, both can behave unexpectedly. Is it true?

让我们一 block 一 block 地分解它。什么是静态类?

A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself.

CLR 如何处理静态类?

As is the case with all class types, the type information for a static class is loaded by the .NET Framework common language runtime (CLR) when the program that references the class is loaded. The program cannot specify exactly when the class is loaded. However, it is guaranteed to be loaded and to have its fields initialized and its static constructor called before the class is referenced for the first time in your program. A static constructor is only called one time, and a static class remains in memory for the lifetime of the application domain in which your program resides.

现在为什么我们可能需要锁定?

基本上,当我们遇到竞争条件时,就需要锁定。当有人读取数据时,其他人可能会同时更改它们。两个单独的线程可以访问共享资源,并且没有任何机制可以防止这种情况发生。为了回答你的问题,你必须首先回答另一个问题。

您的静态方法是否访问共享资源并且可能存在竞争条件?如果是这样,那么您需要使用锁定。否则,不需要。

有关静态类的更多信息,请查看here . 如果您需要有关线程同步技术的更多信息,请查看 here .

关于c# - 静态函数需要锁定机制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32048102/

相关文章:

java - Java 中多线程的替代方案

c++ - 封装线程会产生问题

c# - WPF 自由格式边框控件

C# 日期时间操作

mysql - 如何在 mysql 数据库上进行非侵入性的数字运算?

C套接字,第一个连接的线程关闭剩余的

c++ - 无限循环不会浪费cpu资源吗?

c# - UWP - 在 TextBlock 中垂直居中文本

c# - 为 DropDownList 的第一个条目添加一个空白值

c# - 正则表达式 c# 只有正数