Results 1 to 4 of 4

Thread: API Assistance

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Oct 2002
    Posts
    145

    API Assistance

    Urgent!!!
    I need to catch in my C# program start/end of SQL Server service.
    It's clear that I need to use API function(s) but I can not find wich one may be suitable for my goal... Any ideas/recommendations will be strongly helpful.
    If somebody has code sample, it's really great!!!

    Thanks a lot,

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: API Assistance

    I don't know how you would actually be notified when the service started or stopped. The only solution that I know would work would be to check the status of the service intermittently using a timer. If you want to do that, you could use a call to QueryServiceStatus but I'd say using the .NET ServiceController would be a preferable method.

  3. #3
    Frenzied Member DeadEyes's Avatar
    Join Date
    Jul 2002
    Posts
    1,196

    Re: API Assistance

    This might give you some ideas.
    If IIS is running on your local machine run this code. then manually stop the service.
    Code:
    public static void Main(string[] args)
    {
        try{
    	System.ServiceProcess.ServiceController controller = new ServiceController("iisadmin",".");
    	Console.WriteLine("status:" + controller.Status.ToString());
    	if(controller.Status == ServiceControllerStatus.Running){
    	    controller.WaitForStatus(ServiceControllerStatus.Stopped);
    	    Console.WriteLine("Stopped");
    	}
        }
        catch(Exception ex){
    	Console.WriteLine(ex.Message);
        }
        Console.WriteLine("Fin");
    }

  4. #4
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: API Assistance

    The problem with this method is that ServiceController.WaitForStatus will wait indefinitely until the referenced service enters the specified state. You would have to place this code in a separate thread or your app would just freeze. You could use the overload that takes a timeout period, but then you have to use a timer again to keep calling WaitForStatus. I guess you could use the multi-threaded approach and start a new thread to wait for the opposite status to the current, i.e. if the service is running wait for stopped and if it is stopped wait for running. Then when that status is entered you restart the thread to wait for the opposite status again. You'd have to account for the other possible statuses when checking the current, though.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width