2016-11-16 102 views
2

我只是在尋找確認這個實現是線程安全的。我找不到任何有關在我的WriteLog方法中使用的.Net EventLog.WriteEntry方法是否內部線程安全的信息。是EventLog編寫器線程安全

我需要它是線程安全的上下文是這樣的。我有3個線程我希望他們共享相同的記錄器實例。它們將全部寫入相同的事件日誌源 - 源不能更改。

類中沒有成員變量不同步從訪問它們的不同線程中獲取同步,所以我在考慮是否它是線程安全的答案純​​粹取決於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; 
    } 
} 

回答

1

如果你讀了EventLog類的文檔,你會在底部發現這樣一個字條:

任何公共靜態此類型的成員(在Visual Basic中的Shared)都是線程安全的。任何實例成員不保證是線程安全的。

+0

啊,完美。感謝您的及時回覆。我搜索了WriteLog方法頁面,沒有想到要升級到EventLog類。 – Bunjy