简体   繁体   中英

Alternative to MessageBox.Show() for C# services

In Windows XP, MessageBox.Show() was a viable way of prompting the user when our service failed to start for an unknown reason. However, with Vista and up, services no longer show this message, which is understandable since most times blocking a service with a dialog box is undesirable. What (non-blocking, preferably) alternatives to MessageBox.Show() are available for services?

Windows services should write to the Windows Event log when they encounter errors. Preferably the application log.

You will need to create an event source for the service, and to do this you need admin rights, so this should be done during installation.

使用系统事件日志: http : //support.microsoft.com/kb/307024

You have two basic options:

  1. Create a user-specific startup app that runs in the system tray. This app would connect to and receive messages from the service (this is similar to the way that anti-virus programs operate).

  2. Write all of your messages and exceptions to the event log. You can use the application event log for critical issues and an application-specific event log for informational or diagnostic messages.

The above options are not mutually exclusive and you should always implement #2.

Declaration:

private static TraceSource _traceSource = new TraceSource("YourSourceName");

Usage, see MSDN :

_traceSource.TraceEvent(...);

Configuration:

 <system.diagnostics>
      <sources>
           <source name="YourSourceName" switchValue="All" switchType="System.Diagnostics.SourceSwitch">
                <listeners>
                     <add name="eventLog" />
                </listeners>
      </source>
    <trace autoflush="true">
        <listeners>
            <add name="eventLog" />
        </listeners>
    </trace>
    <sharedListeners>
        <add name="eventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="SourceName" />
    </sharedListeners>
 </system.diagnostics>

Logging is only one correct way to inform user about service issues. The Event Log is preffered loging system to services.

One would usually use the EventLog to log (eg Service Start / Stopped, and errors etc).

If you require additional tracing, use System.Diagnostics.Trace or Debug and then use a tool like DebugView to monitor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM