2012-10-09 56 views
3

我所有的代碼工作正常了這一點:達代碼,不執行和退出沒有錯誤

using System.Diagnostics; 

namespace WebPortalLogging 
{ 
    public static class EventLogging 
    { 
    public static void LogEvent(string origin, string message, EventLogEntryType eventLogEntryType, int eventId) 
     { 
     const string source = "Software"; 
      const string log = "Application"; 

      if (!EventLog.SourceExists(source)) 
       EventLog.CreateEventSource(source, log); 
     EventLog.WriteEntry(source, message, eventLogEntryType, eventId);  
     } 
    } 
} 

我甚至在另一個項目中使用這個類,它工作正常。當它碰到這一行時:

if(!EventLog.SourceExists(source)) EventLog.CreateEventSource(source,log);

它擊中此線並退出。

這裏是什麼在我的輸出:

The thread 'vshost.NotifyLoad' (0x28c) has exited with code 0 (0x0). 
The thread 'vshost.LoadReference' (0x470) has exited with code 0 (0x0). 
'VmBackup.vshost.exe' (Managed (v4.0.30319)): Loaded 'D:\Google Drive\Code\VMBackup\VMBackup\bin\Debug\VmBackup.exe', Symbols loaded. 
'VmBackup.vshost.exe' (Managed (v4.0.30319)): Loaded 'D:\Google Drive\Code\VMBackup\VMBackup\bin\Debug\WebPortalLogging.dll', Symbols loaded. 
The thread '<No Name>' (0xa44) has exited with code 0 (0x0). 
'VmBackup.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 
The thread '<No Name>' (0x107c) has exited with code 0 (0x0). 
The thread '<No Name>' (0x1838) has exited with code 0 (0x0). 
The thread 'vshost.RunParkingWindow' (0xa78) has exited with code 0 (0x0). 
The thread '<No Name>' (0x10e0) has exited with code 0 (0x0). 
The program '[6436] VmBackup.vshost.exe: Program Trace' has exited with code 0 (0x0). 
The program '[6436] VmBackup.vshost.exe: Managed (v4.0.30319)' has exited with code 0 (0x0). 

它沒有達到EventLog.WriteEntry。它也不會輸出到事件日誌中。我已經重新啓動VS2010,並沒有幫助。我提示所有打開的錯誤。

我錯過了什麼?

回答

5

首先,我會使用大括號圍繞您的條件,因爲它有點不清楚,如果EventLog應該寫入條目,如果EventLog沒有源。

if (!EventLog.SourceExists(source)) 
{ 
    EventLog.CreateEventSource(source, log); 
} 

    EventLog.WriteEntry(source, message, eventLogEntryType, eventId); 

也可以嘗試,敷在try/catch塊,看你這是造成程序隨機退出任何未處理的異常。

try { 

    if (!EventLog.SourceExists(source)) 
    { 
      EventLog.CreateEventSource(source, log); 
    } 

    EventLog.WriteEntry(source, message, eventLogEntryType, eventId); 

} catch (Exception e) 
    { 
    Console.WriteLine(e); 
    } 

附加說明:線程'vshost.NotifyLoad' (0x28c) has exited with code 0 (0x0)。 該線程'vshost.LoadReference' (0x470) has exited with code 0 (0x0)。不是錯誤。 Visual Studio告訴你後臺線程已經退出。 0表示線程成功運行。

+0

好點,我會給你一個鏡頭。 – ErocM

+0

用於大括號。如果在我的寵物小偷列表中沒有格式化的sql語句,那麼無情的。 –

+0

我做了兩個,它沒有區別。我沒有發現錯誤。我正在退出「if(!EventLog.SourceExists(source))」並且它不會再繼續。 – ErocM

0

我會懷疑它試圖創建eventLog源並拋出異常,因爲這需要管理員權限。