【问题标题】:Is EventLog writer threadsafe事件日志编写器线程安全吗
【发布时间】:2017-03-30 17:34:59
【问题描述】:

我只是想确认这个实现是线程安全的。我找不到关于我在 WriteLog 方法中使用的静态 .Net EventLog.WriteEntry 方法是否在内部线程安全的任何信息。

我需要它是线程安全的上下文是这样的。我有 3 个线程,我希望它们共享同一个 logwriter 实例。它们都将写入同一个事件日志源 - 无法更改源。

类中没有成员变量可以与访问它们的不同线程不同步,所以我认为是否是线程安全的答案完全取决于 EventLog.WriteEntry 方法本身是否是线程安全的。

如果有人能证实这一点,我将不胜感激。非常感谢。

public class EventLogWriter : ILogWriter
{
    private string EventLogSourceName;
    public EventLogWriter() { EventLogSourceName = System.Configuration.ConfigurationManager.AppSettings["CustomEventLogSourceName"]; }
    public EventLogWriter(string eventLogSourceName) { EventLogSourceName = eventLogSourceName; }

    // ILogWriter interface method
    public void WriteLog(string content, LogType logType)
    {
        // maps from our logType to the event log type
        EventLogEntryType eventLogType = GetEventLogType(logType);
        EventLog.WriteEntry(this.EventLogSourceName, content.ToString(), eventLogType, 0, (short)logType);
    }

    protected EventLogEntryType GetEventLogType(LogType logType)
    {
        EventLogEntryType eventLogType;
        switch (logType)
        {
            case LogType.UnhandledException:
                eventLogType = EventLogEntryType.Error;
                break;
            case LogType.HandledException:
                eventLogType = EventLogEntryType.Warning;
                break;
            case LogType.Warning:
                eventLogType = EventLogEntryType.Warning;
                break;
            case LogType.Information:
                eventLogType = EventLogEntryType.Information;
                break;
            case LogType.Verbose:
                eventLogType = EventLogEntryType.Information;
                break;
            default:
                eventLogType = EventLogEntryType.Error;
                break;
        }
        return eventLogType;
    }
}

【问题讨论】:

    标签: c# .net multithreading thread-safety


    【解决方案1】:

    如果您阅读 EventLog 类的文档,您会在底部找到此注释:

    此类型的任何公共静态(在 Visual Basic 中为共享)成员都是线程安全的。不保证任何实例成员都是线程安全的。

    【讨论】:

    • 啊,完美。感谢您的及时回复。我搜索了WriteLog方法页面,没想到要上EventLog类。
    猜你喜欢
    • 1970-01-01
    • 2012-08-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-20
    • 2014-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多