Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3322986
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 17, 20262026-05-17T23:14:54+00:00 2026-05-17T23:14:54+00:00

I am developing a Windows Service application of some complexity, and need to have

  • 0

I am developing a Windows Service application of some complexity, and need to have a way of gracefully transitioning between states. Since each state might need initialization / cleaning up, there must be a mechanism that coordinates the transitions between them and makes sure only valid states can be reached from any given state. The states in question are the familiar states of a Windows Service:

Stopped|Running|Paused|StopPending|StartPending|PausePending|ContinuePending

I have developed a system that seems to do this properly, but I am curious whether it has flaws that I just haven’t stumbled over yet and/or if there are more tried-and-tested patterns / best practices that I could or should use instead.

This is implemented in a Bootstrapper class that exposes methods corresponding to the commands I should expect from a Windows Service: Start, Stop, Pause, Continue (so that the Service’s OnStart command will simply call the class’ Start method, OnStop will call Stop etc):

In the Service code (this is VB.Net, but I had to use // for comments here, since ‘ seemed to mess things up in the code listing):

Sub OnStart()
    Bootstrapper.Start()
End Sub

In the Start() method of my class (I bypass threading and exception handling and other logic for simplicity here):

Public Sub Start()
    If RequestState(State.Running) = True Then
        // Log success
    Else
        // Log failure
    End If
End Sub

Then, inside my class, there is a similar set of private OnStart(), OnStop(), OnPause() and OnContinue() methods that perform the actual initialization / cleanup for each state:

Private Function OnStart() As Boolean
    SetState(State.StartPending)
        // Do something
    Return SetState(State.Running)
End Function

As you can see above, there are calls being made to two other methods – RequestState() and SetState(). That’s where the logic actually takes place, and it works as follows:

A command is being sent to the application (Start, Stop, Pause or Continue). The receiving method calls RequestState() with the desired end state passed as a parameter. If that state was reachable it returns True, otherwise False.

RequestState() will use Select constructs to determine the right action, based on the current state and the requested state.

SetState() actually sets the state of the application, and after doing so, checks whether there is some ‘next’ state ‘queued up’ (this is so that a StartPending process will be able to finish and end up in a Running state, before a Pause command is issued).

Forgive me if I introduce these methods in a jumbled order, but from where I sit, it seemed like the right way to introduce the functionality. Here are the RequestState() and SetState() methods (sorry for the sheer length, but I felt it was needed for completeness):

Private _currentState As State
Private _nextState As State

Private Function RequestState(ByVal requestedState As State) As Boolean
    Select Case requestedState
        Case State.StartPending, State.StopPending, State.PausePending, State.ContinuePending, State.Exception, State.None
            Throw New ArgumentException(requestedState.ToString & " cannot be requested directly.")
        Case Else

            _nextState = requestedState

            Select Case _currentState
                Case State.Exception
                    Return False

                Case State.Stopped
                    Select Case requestedState
                        Case State.Stopped
                            Return True
                        Case State.Running
                            Return OnStart()
                        Case Else
                            Return False
                    End Select

                Case State.Running
                    Select Case requestedState
                        Case State.Stopped
                            Return OnStop()
                        Case State.Running
                            Return True
                        Case State.Paused
                            Return OnPause()
                        Case Else
                            Return False
                    End Select

                Case State.Paused
                    Select Case requestedState
                        Case State.Stopped
                            Return OnStop()
                        Case State.Running
                            Return OnContinue()
                        Case State.Paused
                            Return True
                        Case Else
                            Return False
                    End Select

                Case State.StartPending
                    Select Case requestedState
                        Case State.Stopped
                            _nextState = State.Stopped
                            Return True
                        Case State.Running
                            Return True
                        Case State.Paused
                            _nextState = State.Paused
                            Return True
                        Case Else
                            Return False
                    End Select

                Case State.StopPending
                    Select Case requestedState
                        Case State.Stopped
                            Return True
                        Case State.Running
                            _nextState = State.Running
                            Return True
                        Case Else
                            Return False
                    End Select

                Case State.ContinuePending
                    Select Case requestedState
                        Case State.Stopped
                            _nextState = State.Stopped
                            Return True
                        Case State.Running
                            Return True
                        Case State.Paused
                            _nextState = State.Paused
                            Return True
                        Case Else
                            Return False
                End Select

                Case State.PausePending
                    Select Case requestedState
                        Case State.Stopped
                            _nextState = State.Stopped
                            Return True
                        Case State.Running
                            _nextState = State.Running
                            Return True
                        Case State.Paused
                            Return True
                        Case Else
                            Return False
                    End Select

                Case Else
                    Return False

            End Select
    End Select
End Function

Private Function SetState(ByVal newState As State) As Boolean
    _currentState = newState
    If newState = State.Running OrElse newState = State.Stopped OrElse newState = State.Paused Then
        If _currentState = _nextState Then
            Return True
        End If
        Return RequestState(_nextState)
    Else
        Return True
    End If
End Function
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-17T23:14:54+00:00Added an answer on May 17, 2026 at 11:14 pm

    I’d say its ok as-is. There aren’t many states and its reasonably easy to follow. I’d say there are some places where you can make the code a bit shorter, but otherwise its not too bad.

    However, it might be easier creating a real state table. Start by mapping your state table out in a grid like this:

    Start State        Requested State      State Changed?
    -----------        ---------------      --------------
    Exception          { any }              False
    Stopped            Running              OnStart()
    Paused             Stopped              OnStop()
    Paused             Running              OnPause()
    StartPending       Running              True
    StartPending       Paused               True
    etc
    

    Now to convert this into code, consider that this is basically a Dictionary<State, Dictionary<State, Func<bool>>>, where the outer key is your StartState, outer Value is your transition table.

    This code is not tested, but should give you a general idea of where to start (using C# since my VB-fu is rusty):

    public bool RequestState(State requestedState)
    {
        _nextState = requestedState;
        if (requestedState == currentState)
            return true;
    
        var stateTransitions = new Dictionary<State, Dictionary<State, Func<bool>>>
        {
            { State.Exception, new Dictionary<State, Func<bool>(),
            { State.Stopped, new Dictionary<State, Func<bool>>
                {
                    { State.Running, () => OnStart() }
                }
            },
            { State.Paused, new Dictionary<State, Func<bool>>
                {
                    { State.Stopped, () => OnStop() },
                    { State.Running, () => OnPause() },
                }
            },
            { State.StartPending, new Dictionary<State, Func<bool>>
                {
                    { State.Running, () => true },
                    { State.Paused, () => true },
                }
            },
            // remaining states
        };
    
        var transition = stateTransitions[currentState];
        Func<bool> transitionAction;
        if (transition.TryGetValue(requestedState, out transitionAction))
            return transitionAction();
        return false;
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm developing a twitter application for Windows Phone 7 and have been doing some
I'm developing and application that runs as a Windows service. There are other components
I am developing a Windows .NET application (WinForms) and I need to simulate a
I am developing a small windows app, but have some trouble deciding whether to
I have been developing a C# windows form application in XP. It all works
I am developing large data collecting ASP.Net/Windows service application-pair that uses Microsoft SQL Server
I'm getting close to desperate.. I am developing a field service application for Windows
I've been developing a remote desktop application which runs as a Windows service, and
What is the best way to start developing Windows Mobile Professional applications in Python?
We're developing a windows mobile 6.1 application and would like to make the user

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.