Получение "... уже зарегистрировано ..." от EventLog.CreateEventSource, хотя я проверяю! EventLog.SourceExists - PullRequest
9 голосов
/ 22 июля 2010

Мой следующий код не работает с "... уже зарегистрирован как источник на локальном компьютере", хотя я сначала проверяю:

lock ( eventLock )
{
    string eventLog = Constants.EventLogPL;
    string eventSrc = Constants.EventSrcPL;

    if (!EventLog.Exists(eventLog))
    {
        if (!EventLog.SourceExists(eventSrc))
        {
            try
            {
                EventLog.CreateEventSource(eventSrc, eventLog);
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.Message);
            }
        }
    }
}

Я бы подумал, что моего звонка на !EventLog.SourceExists было бы достаточно, чтобы предотвратить мою ошибку! Я нахожусь на 2010 .NET 4 и Windows 7 64 компиляции на любой процессор.

Редактировать: Обновлен код для получения констант местным жителям, чтобы проверить, не изменились ли они, и использовать блокировку, чтобы убедиться, что только один поток может тестировать и создавать. Код все еще терпит неудачу с той же ошибкой.

Ответы [ 2 ]

22 голосов
/ 22 июля 2010

Обнаружена проблема после входа в Sysinternals 'Process Monitor , немного больше:

Вызов EventLog.Exists("MyLog");

Имя журнала не найдено, как и ожидалось в:

KLM \ System \ CurrentControlSet \ services \ eventlog \ MyLog

Вызов EventLog.SourceExists("MySource");

Проверяет несколько мест, имя не найдено, как ожидалось:

HKLM \ System \ CurrentControlSet \ services \ eventlog \ Application \ MySource
HKLM \ System \ CurrentControlSet \ services \ eventlog \ HardwareEvents \ MySource
HKLM \ System \ CurrentControlSet \ services \ eventlog \ Internet Explorer \ MySource
HKLM \ System \ CurrentControlSet \ services \ eventlog \ Служба управления ключами \ MySource
HKLM\ System \ CurrentControlSet \ services \ eventlog \ Media Center \ MySource
HKLM \ System \ CurrentControlSet \ services \ eventlog \ ODiag \ MySource
HKLM \ System \ CurrentControlSet \services \ eventlog \ OSession \ MySource
HKLM \ System \ CurrentControlSet \ services \ eventlog \ Security \ MySource
HKLM \ System \ CurrentControlSet \ services \ eventlog \ System \ MySource
HKLM \ System \ CurrentControlSet \ services \ eventlog \VisualSVNServer \ MySource
HKLM \ System \ CurrentControlSet \ services \ eventlog \ Windows PowerShell \ MySource
HKLM \ System \ CurrentControlSet \ services \ eventlog \ Application \ MySource
HKLM \ System \ CurrentControlSet \ services \ eventlog \ HardwareEvents \ MySource
HKLM \ System \ CurrentControlSet \ services \ eventlog \ Internet Explorer \ MySource
HKLM \ System \ CurrentControlSet \ services \ eventlog \ Служба управления ключами \ MySource
HKLM \ System \ CurrentControlSet \ services \ eventlog \ Медиа-центр \ MySource
HKLM\ System \ CurrentControlSet \ services \ eventlog \ ODiag \ MySource
HKLM \ System \ CurrentControlSet \ services \ eventlog \ OSession \ MySource
HKLM \ System \ CurrentControlSet \ services\ канунаntlog \ Security \ MySource
HKLM \ System \ CurrentControlSet \ services \ eventlog \ System \ MySource
HKLM \ System \ CurrentControlSet \ services \ eventlog \ VisualSVNServer \ MySource
HKLM \ System \ CurrentControlSet \ services \ eventlog \ Windows PowerShell \ MySource
HKLM \ System \ CurrentControlSet \ services \ eventlog \ MyLog

Тем не менее, вызов EventLog.CreateEventSource("MySource", "MyLog");

Находит MyLog в следующем месте реестра и ошибки:

HKLM \ System \ CurrentControlSet \ services \ eventlog \ Application \ MyLog

Удаление "HKLM \ System \ CurrentControlSet \ services \ eventlog \ Application \ MyLog" и повторный запуск исправили мою проблему!

Похоже, .Exists не выглядит во всех местах .CreateEvent делает!

2 голосов
/ 22 июля 2010
//0 for false, 1 for true.
private static int usingResource = 0;

if (!EventLog.SourceExists(Constants.EventSrcPL))
{
    //0 indicates that the method is not in use.
    if (0 == Interlocked.Exchange(ref usingResource, 1))
    {
        if (!EventLog.SourceExists(Constants.EventSrcPL))
        {
            try
            {
                EventLog.CreateEventSource(Constants.EventSrcPL, Constants.EventLogPL);
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.Message);
                //Release the lock
                Interlocked.Exchange(ref usingResource, 0);
            }
        }
    }
}
else
{
    usingResource = 0;
}

Не решает проблему, когда источник создается другим приложением в то время, когда вы обращаетесь к журналу событий.

Отредактировано : внесены изменения, которые учитываютзадержка создания EventSource.

...