如果我在类中将像记录器对象这样的对象定义为静态对象,则调用如下方法:
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/