c# - 同时请求多个请求的静态成员和实例方法

标签 c# .net static

如果我在类中将像记录器对象这样的对象定义为静态对象,则调用如下方法:

public class Manager
{    
    private static ClientLogManager log = new ClientLogManager();

    public void Log(string Message)
    {
         log.Debug(string Message);
    }
}

这是在类库项目中定义的。

我的理解是静态变量在这个应用的所有请求之间是共享的,所以日志对象是共享的。但是Debug这个方法本身不是静态的,而是对象是静态的,所以这个方法只会有一个实例。对吗?

如果有很多用户同时调用这段代码,如果2个请求同时调用log.Debug方法,第2个请求的消息是否可以覆盖第1个请求的消息?

还有,用单例代替这个更好吗?不是每个请求一个 Singleton 对象吗?

这是ClientLogManager代码

  public class ClientLogManager
    {
        #region Member Variables

        private static readonly ILog _log = LogManager.GetLogger(typeof(ClientLogManager));

        #endregion

        #region Constructors

        public ClientLogManager()
        {

        }

        #endregion

        #region Public Methods

        public void Debug(string message)
        {
            _log.Debug(message);
        }

        #endregion
    }

最佳答案

If a lot of users are calling this code at the same time, if 2 requests are calling the log.Debug method at the same time, can the message of the 2nd request overwrite the message of the 1st request?

是的,除非记录器是专门为支持这一点而编写的。大多数记录器都设计为支持此功能,因此除非您从头开始自己制作,否则它可能会在内部同步所有写入(这样您就不必这样做)。如果您不确定,您应该查看您正在使用的特定记录器的文档,看看它是否支持或在同时写入时中断。

关于c# - 同时请求多个请求的静态成员和实例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13075254/

相关文章:

c# - 我可以从 64 位应用程序以 32 位运行 C# 程序集 (dll) 吗?

c# - 异步队列处理的 CPU 使用率几乎达到 100%

访问私有(private)变量的 Java 静态方法

c# - 文本框和线程

C# var关键字混淆: Type 'object' does not contain a definition for. ..错误

.net - Entity Framework SQLite 错误 1 ​​: 'no such table: __EFMigrationsHistory'

java - java中的抽象静态类给出错误修饰符的非法组合

javascript - javascript静态类继承非静态类的表现

c# - 在 Dialog 类中访问 DbContext 的最佳方法是什么

c# - 如何用一定长度的空行初始化DataTable?