开发者

error while stopping windows service programmatically

开发者 https://www.devze.com 2023-03-05 03:35 出处:网络
I have a windows service. In the OnStart method, I am performing some operation and if one of the operation fails, I want service to stop. In the Catch block I am writing below mentioned code:

I have a windows service. In the OnStart method, I am performing some operation and if one of the operation fails, I want service to stop. In the Catch block I am writing below mentioned code:

var srvc = new System.ServiceProcess.ServiceController("Scv1", "localhost");
srvc.Stop();
srvc.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped);
开发者_StackOverflow社区

It does the job well but windows shows me a messagebox:

---------------------------
Services
---------------------------
The xxx service on Local Computer started and then stopped. Some services stop automatically if they are not in use by other services or programs.
---------------------------
OK   
---------------------------

Am I doing something wrong here? How do I suppress the messagebox?


I created a basic test service in C#, installed it on Windows 7, and then tried to start it.

using System.ServiceProcess;

public class MyService : ServiceBase
{
  static void Main()
  {
    System.ServiceProcess.ServiceBase.Run( new MyService() );
  }

  protected override void OnStart( string[] args )
  {
    bool failed = true;
    // Do stuff...
    // Oops, we failed! Time to stop!
    if( failed ) {
      base.Stop();
      return;
    }
    base.OnStart( args );
  }
}

When it fails, yes, I do see the message box that you describe. This message box is not part of your service -- the Services window is showing that. If you were to open an administrator command prompt and type the following:

net start Scv1

Then you would see a text-based error message instead of a message box.

In either case, you are running a program that asks the SCM to start your service. Your service failed to start. That failure is reported back to the program. The program has decided to display an error message to inform the user. That is beyond your control.


You can actually check the event handler. It will intimate you the mistake you have done in the configuration file. Some syntax error in the configuration file will be the reason for this kind of message box.

0

精彩评论

暂无评论...
验证码 换一张
取 消