Before calling Service.Stop

StewartBW 1,720 Reputation points
2025-06-14T14:41:11.9066667+00:00

Hi experts,

Using MyService As New ServiceController("BlahService")
  If MyService.CanStop = True AndAlso MyService.Status = ServiceControllerStatus.Running Then MyService.Stop()
  MyService.Close()
End Using

Is my usage correct? I mean before calling Service.Stop should I check both for Service.CanStop and Service.Status? Thanks.

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,889 questions
0 comments No comments
{count} votes

Accepted answer
  1. Marcin Policht 49,255 Reputation points MVP Volunteer Moderator
    2025-06-14T14:44:15.9633333+00:00

    Your intention is mostly correct, but looks like there's a logical mistake in your condition. You're checking:

    MyService.CanStop = True AndAlso MyService.Status <> ServiceControllerStatus.Running
    

    This means only stop the service if it can be stopped AND it's not running, which doesn't seem to make much sense, because ServiceController.Stop() only applies to a running service. Instead, you should only stop the service if it's running and can be stopped. So, your condition should be:

    If MyService.CanStop AndAlso MyService.Status = ServiceControllerStatus.Running Then
        MyService.Stop()
    End If
    

    If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.

    hth

    Marcin

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.