4

Consider the following:

public class SomeService
{
    public Task StartAsync()
    {
        return Task.Factory
            .StartNew(() => DoStartup());
    }

    public Task StopAsync()
    {
        return Task.Factory
            .StartNew(() => DoShutdown());
    }
}

The problem with the above is that if multiple calls to either StartAsync or StopAsync are made then multiple tasks will be created to start/stop the service. Realistically, one would only want a single start/stop task active at any one time. To that end, I usually do something like this:

public class SomeService
{
    private readonly object startSync = new object();
    private readonly object stopSync = new object();
    private Task startTask;
    private Task stopTask;

    public Task StartAsync()
    {
        var startTaskLocal = this.startTask;

        if (startTaskLocal != null)
        {
            return startTaskLocal;
        }

        lock (this.startSync)
        {
            if (this.startTask != null)
            {
                return this.startTask;
            }

            this.startTask = Task.Factory
                .StartNew(() => DoStartup())
                .Then(x =>
                    {
                        lock (this.stopSync)
                        {
                            this.stopTask = null);
                        }
                    });

            return this.startTask;
        }
    }

    public Task StopAsync()
    {
        // similar pattern to above
    }
}

Now whilst this works, it's kind of ugly. Before I get too far ahead of myself in trying to encapsulate this pattern into something small and reusable, I'm wondering whether there is an already established way of doing so that I am unaware of?

PS. I extend this idea even further by having StartAsync wait for any outstanding StopAsync call, and vice-versa. That means that only one start OR stop operation can be in progress at any one time. This is pretty easy to do via task composition. If I can first find out whether there's an established way of neatly achieving the above, I can then figure out whether it fits in with this extended behavior.

6
  • Hard to know without context, but not having them async would make it a little simpler. I'm guessing that's not a viable option, but mentioning just in case it is. :) Jul 24, 2012 at 16:23
  • Just to verify the intent, if another async call comes in while one is still being processed, you want it to be ignored instead of queued up to be run after the current one completes? Jul 24, 2012 at 16:25
  • @James: not having them async is not an option, but wouldn't really help anyway. After all, multiple threads could call the non-asynchronous version, leaving me in much the same boat. Yes, the intent is to have a single start task active at any one point. If another call to start is made when an existing task is running, the existing task is returned. Jul 24, 2012 at 16:30
  • Not relevant to your question, but what is Then() and how does it differ from ContinueWith()? And why don't you combine the two pieces of code into one lambda?
    – svick
    Jul 24, 2012 at 18:19
  • Then only executes if the antecedent tasks run to completion, whereas ContinueWith will always execute (continuation options permitting). Moreover, Then yields a Task lazily, whereas ContinueWith works with delegates (reference link coming). They are not combined into one lambda because it's just an example. In reality, there are several steps involved in starting, many of which are implemented as async methods in other layers of the application. This is where Then really shines because the alternative is to call Wait inside a ContinueWith, which blocks the thread. Jul 24, 2012 at 19:37

4 Answers 4

1

You could use the State Machine pattern. When the code enters the AsyncStart, set state to Starting. I recommend a callback that sets the object's state to Running.

Provide the same for Stopping, Stopped.

So internal to your service, you may have a ServiceState object. Prior to calling AsyncStart/AsyncStop, check the current state.

Update
... another way may be to store and check the Cancellation Token. There are a myriad of samples on how to use the CancellationToken. This is just off the top of my head and not a confirmation that this is necessarily the best way.

5
  • This makes sense and is the likely means of encapsulating this into something reusable. However, I was predominantly wondering whether something already exists that does this for you. eg. some hidden gem in TPL or in a utility library for TPL. Jul 24, 2012 at 17:52
  • You could store a CancellationToken: msdn.microsoft.com/en-us/library/… ...
    – IAbstract
    Jul 24, 2012 at 19:06
  • I don't follow. I know what a cancellation token is and how to use it, but I don't see how it's relevant to my question. I don't want to cancel any outstanding task, I want the caller to receive that same task. Imagine 20 threads all requesting the service start at the same time. The service only starts itself the once and passes the same startup task back to all callers. Jul 24, 2012 at 19:31
  • But you can check if a CancellationToken is not null, is completed, is cancelled, etc. It was just an alternate thought and I wasn't sure if it would provide what you want.
    – IAbstract
    Jul 24, 2012 at 19:35
  • I see. No, cancellation tokens don't help. If all you have is a cancellation token, all you can do is check whether cancellation has been requested against that token. Your original thought on using a state machine is apt, but it's pretty much what I'm doing. Sure, it could be a little cleaner by using an enum or the likes, but it still a state machine - it just uses the Task instances to track the state instead. The point of my question was to get away from having to implement this at all. eg. just call something like return Task.Factory.StartNewOrUseExisting(...) Jul 24, 2012 at 19:46
1

I finally got around to addressing this issue in my code base, and figured I'd share my solution here. A quick explanation: I have a StateMachineTaskFactory<T> class, where T defines the valid states (normally an enumeration). This task factory allows you to register valid transitions (eg. when transitioning to Started state, use Starting whilst the transition is in progress) and enact a transition. It guarantees state machine semantics whilst maintaining an asynchronous API. It basically formalizes the state machine present in my original code, doing so in a robust and reusable fashion.

First, here's an example of how it is used in the use case presented in my question:

public enum ServiceState
{
    Uninitialized,
    Initializing,
    Initialized,
    Starting,
    Started,
    Stopping,
    Stopped
}

public class SomeService
{
    private readonly StateMachineTaskFactory<ServiceState> stateMachineTaskFactory;

    public Service()
    {
        this.stateMachineTaskFactory = new StateMachineTaskFactory<ServiceState>();
        this.stateMachineTaskFactory.RegisterTransition(ServiceState.Initializing, ServiceState.Initialized, this.OnInitializeAsync);
        this.stateMachineTaskFactory.RegisterTransition(ServiceState.Starting, ServiceState.Started, this.OnStartAsync);
        this.stateMachineTaskFactory.RegisterTransition(ServiceState.Stopping, ServiceState.Stopped, this.OnStopAsync);
    }

    // we don't support cancellation in our initialize API
    public Task InitializeAsync()
    {
        return this.stateMachineTaskFactory.TransitionTo(ServiceState.Initialized);
    }

    public Task StartAsync(CancellationToken cancellationToken = default(CancellationToken))
    {
        return this.stateMachineTaskFactory.TransitionTo(ServiceState.Started, cancellationToken);
    }

    public Task StopAsync(CancellationToken cancellationToken = default(CancellationToken))
    {
        return this.stateMachineTaskFactory.TransitionTo(ServiceState.Stopped, cancellationToken);
    }

    // even though we don't support cancellation during initialization, we'll still get a cancellation token, but it will CancellationToken.None
    private Task OnInitializeAsync(CancellationToken cancellationToken, object state)
    {
        // return a Task that performs the actual work involved in initializing
    }

    private Task OnStartAsync(CancellationToken cancellationToken, object state)
    {
        // return a Task that performs the actual work involved in starting, passing on the cancellation token as relevant
    }

    private Task OnStopAsync(CancellationToken cancellationToken, object state)
    {
        // return a Task that performs the actual work involved in stopping, passing on the cancellation token as relevant
    }
}

There is more power and flexibility available than evident in the above example usage, but it's probably the normal use case.

Sorry for the following wall of code. I've removed API docs to improve readability. There are a couple of utility classes I have not included, but they're pretty self-explanatory.

[Serializable]
public sealed class StateTransitionForbiddenException<T> : InvalidOperationException
    where T : struct
{
    private readonly T targetState;
    private readonly T state;

    public StateTransitionForbiddenException()
    {
    }

    public StateTransitionForbiddenException(string message)
        : base(message)
    {
    }

    public StateTransitionForbiddenException(string message, Exception innerException)
        : base(message, innerException)
    {
    }

    public StateTransitionForbiddenException(T targetState, T state)
        : base("A transition to state '" + targetState + "' was forbidden by the validate transition callback.")
    {
        this.targetState = targetState;
        this.state = state;
    }

    public StateTransitionForbiddenException(string message, T targetState, T state)
        : base(message)
    {
        this.targetState = targetState;
        this.state = state;
    }

    private StateTransitionForbiddenException(SerializationInfo info, StreamingContext context)
        : base(info, context)
    {
        this.targetState = (T)info.GetValue("TargetState", typeof(T));
        this.state = (T)info.GetValue("State", typeof(T));
    }

    public T TargetState
    {
        get { return this.targetState; }
    }

    public T State
    {
        get { return this.state; }
    }

    public override void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        base.GetObjectData(info, context);

        info.AddValue("TargetState", this.targetState);
        info.AddValue("State", this.state);
    }
}

[DebuggerDisplay("{OldState} -> {NewState}")]
public sealed class StateChangedEventArgs<T> : EventArgs
    where T : struct
{
    private readonly T oldState;
    private readonly T newState;

    public StateChangedEventArgs(T oldState, T newState)
    {
        this.oldState = oldState;
        this.newState = newState;
    }

    public T OldState
    {
        get { return this.oldState; }
    }

    public T NewState
    {
        get { return this.newState; }
    }
}

public delegate Task CreateTaskForTransitionCallback(CancellationToken cancellationToken, object state);

public delegate bool ValidateTransitionCallback<T>(T currentState)
    where T : struct;

public class StateMachineTaskFactory<T> : TaskFactory
    where T : struct
{
    private static readonly ExceptionHelper exceptionHelper = new ExceptionHelper(typeof(StateMachineTaskFactory<>));
    private readonly ConcurrentDictionary<T, TransitionRegistrationInfo> transitionRegistrations;
    private readonly object stateSync;

    // the current state
    private T state;

    // the state to which we're currently transitioning
    private T? transitionToState;

    // the task performing the transition
    private Task transitionToTask;

    public StateMachineTaskFactory()
        : this(default(T))
    {
    }

    public StateMachineTaskFactory(T startState)
    {
        this.transitionRegistrations = new ConcurrentDictionary<T, TransitionRegistrationInfo>();
        this.stateSync = new object();
        this.state = startState;
    }

    public event EventHandler<StateChangedEventArgs<T>> StateChanged;

    public T State
    {
        get
        {
            return this.state;
        }

        private set
        {
            if (!EqualityComparer<T>.Default.Equals(this.state, value))
            {
                var oldState = this.state;
                this.state = value;
                this.OnStateChanged(new StateChangedEventArgs<T>(oldState, value));
            }
        }
    }

    public void RegisterTransition(T beginTransitionState, T endTransitionState, CreateTaskForTransitionCallback createTaskCallback)
    {
        createTaskCallback.AssertNotNull("factory");

        var transitionRegistrationInfo = new TransitionRegistrationInfo(beginTransitionState, createTaskCallback);
        var registered = this.transitionRegistrations.TryAdd(endTransitionState, transitionRegistrationInfo);
        exceptionHelper.ResolveAndThrowIf(!registered, "transitionAlreadyRegistered", endTransitionState);
    }

    public Task TransitionTo(T endTransitionState, CancellationToken cancellationToken = default(CancellationToken), ValidateTransitionCallback<T> validateTransitionCallback = null, object state = null)
    {
        lock (this.stateSync)
        {
            if (EqualityComparer<T>.Default.Equals(this.state, endTransitionState))
            {
                // already in the requested state - nothing to do
                return TaskUtil.FromResult(true);
            }
            else if (this.transitionToState.HasValue && EqualityComparer<T>.Default.Equals(this.transitionToState.Value, endTransitionState))
            {
                // already in the process of transitioning to the requested state - return same transition task
                return this.transitionToTask;
            }
            else if (this.transitionToTask != null)
            {
                // not in the requested state, but there is an outstanding transition in progress, so come back to this request once it's done
                return this.transitionToTask.Then(x => this.TransitionTo(endTransitionState, cancellationToken, validateTransitionCallback, state));
            }
            else if (validateTransitionCallback != null && !validateTransitionCallback(this.State))
            {
                // transition is forbidden, so return a failing task to that affect
                var taskCompletionSource = new TaskCompletionSource<bool>();
                var exception = new StateTransitionForbiddenException<T>(endTransitionState, this.State);
                taskCompletionSource.TrySetException(exception);
                return taskCompletionSource.Task;
            }

            // else, need to transition to the chosen state
            TransitionRegistrationInfo transitionRegistrationInfo;
            var result = this.transitionRegistrations.TryGetValue(endTransitionState, out transitionRegistrationInfo);
            exceptionHelper.ResolveAndThrowIf(!result, "transitionNotRegistered", endTransitionState);

            var beginTransitionState = transitionRegistrationInfo.BeginTransitionState;
            var task = transitionRegistrationInfo.TaskFactory(cancellationToken, state);
            exceptionHelper.ResolveAndThrowIf(task == null, "taskFactoryReturnedNull", endTransitionState);

            var previousState = this.State;
            this.State = beginTransitionState;
            this.transitionToState = endTransitionState;
            this.transitionToTask = task
                .ContinueWith(
                    x =>
                        {
                            if (x.IsFaulted || cancellationToken.IsCancellationRequested)
                            {
                                // faulted or canceled, so roll back to previous state
                                lock (this.stateSync)
                                {
                                    this.State = previousState;
                                    this.transitionToState = null;
                                    this.transitionToTask = null;
                                }

                                if (x.IsFaulted)
                                {
                                    throw x.Exception;
                                }

                                cancellationToken.ThrowIfCancellationRequested();
                            }
                            else
                            {
                                // succeeded, so commit to end state
                                lock (this.stateSync)
                                {
                                    this.State = endTransitionState;
                                    this.transitionToState = null;
                                    this.transitionToTask = null;
                                }
                            }
                        });

            return this.transitionToTask;
        }
    }

    protected virtual void OnStateChanged(StateChangedEventArgs<T> e)
    {
        this.StateChanged.Raise(this, e);
    }

    private struct TransitionRegistrationInfo
    {
        private readonly T beginTransitionState;
        private readonly CreateTaskForTransitionCallback taskFactory;

        public TransitionRegistrationInfo(T beginTransitionState, CreateTaskForTransitionCallback taskFactory)
        {
            this.beginTransitionState = beginTransitionState;
            this.taskFactory = taskFactory;
        }

        public T BeginTransitionState
        {
            get { return this.beginTransitionState; }
        }

        public CreateTaskForTransitionCallback TaskFactory
        {
            get { return this.taskFactory; }
        }
    }
}

And, for completeness, my unit tests:

public sealed class StateMachineTaskFactoryFixture
{
    #region Supporting Enums

    private enum State
    {
        Undefined,
        Starting,
        Started,
        Stopping,
        Stopped
    }

    #endregion

    [Fact]
    public void default_ctor_uses_default_value_for_start_state()
    {
        var factory = new StateMachineTaskFactory<State>();
        Assert.Equal(State.Undefined, factory.State);
    }

    [Fact]
    public void ctor_can_set_start_state()
    {
        var factory = new StateMachineTaskFactory<State>(State.Stopped);
        Assert.Equal(State.Stopped, factory.State);
    }

    [Fact]
    public void register_transition_throws_if_factory_is_null()
    {
        var factory = new StateMachineTaskFactory<State>();
        Assert.Throws<ArgumentNullException>(() => factory.RegisterTransition(State.Starting, State.Started, null));
    }

    [Fact]
    public void register_transition_throws_if_transition_already_registered()
    {
        var factory = new StateMachineTaskFactory<State>();
        factory.RegisterTransition(State.Starting, State.Started, (ct, o) => TaskUtil.FromResult(true));

        var ex = Assert.Throws<InvalidOperationException>(() => factory.RegisterTransition(State.Starting, State.Started, (ct, o) => TaskUtil.FromResult(true)));
        Assert.Equal("A transition to state 'Started' has already been registered.", ex.Message);
    }

    [Fact]
    public void transition_to_throws_if_no_transition_registered_for_state()
    {
        var factory = new StateMachineTaskFactory<State>();

        var ex = Assert.Throws<InvalidOperationException>(() => factory.TransitionTo(State.Started));
        Assert.Equal("No transition to state 'Started' has been registered.", ex.Message);
    }

    [Fact]
    public void transition_to_throws_if_task_factory_returns_null()
    {
        var factory = new StateMachineTaskFactory<State>();
        factory.RegisterTransition(State.Starting, State.Started, (ct, o) => null);

        var ex = Assert.Throws<InvalidOperationException>(() => factory.TransitionTo(State.Started));
        Assert.Equal("Task factory for end state 'Started' returned null.", ex.Message);
    }

    [Fact]
    public void transition_to_returns_same_task_if_called_multiple_times_whilst_initial_task_is_still_in_progress()
    {
        var factory = new StateMachineTaskFactory<State>();
        factory.RegisterTransition(State.Starting, State.Started, (ct, o) => TaskUtil.Delay(TimeSpan.FromMilliseconds(250)));

        var initialTask = factory.TransitionTo(State.Started);

        Assert.Equal(initialTask, factory.TransitionTo(State.Started));
        Assert.Equal(initialTask, factory.TransitionTo(State.Started));
        Assert.Equal(initialTask, factory.TransitionTo(State.Started));

        Assert.True(initialTask.Wait(TimeSpan.FromSeconds(3)));
    }

    [Fact]
    public void transition_to_returns_completed_task_if_already_in_desired_state()
    {
        var factory = new StateMachineTaskFactory<State>();
        factory.RegisterTransition(State.Starting, State.Started, (ct, o) => TaskUtil.FromResult(true));

        factory.TransitionTo(State.Started).Wait();

        Assert.Equal(TaskStatus.RanToCompletion, factory.TransitionTo(State.Started).Status);
    }

    [Fact]
    public void transition_to_passes_any_state_to_task_creation_function()
    {
        var factory = new StateMachineTaskFactory<State>();
        string receivedState = null;
        factory.RegisterTransition(
            State.Starting,
            State.Started,
            (ct, o) =>
            {
                receivedState = o as string;
                return TaskUtil.FromResult(true);
            });

        factory.TransitionTo(State.Started, CancellationToken.None, null, "here is the state").Wait();

        Assert.Equal("here is the state", receivedState);
    }

    [Fact]
    [SuppressMessage("Microsoft.Naming", "CA2204", Justification = "It's not a word - it's a format string!")]
    public void transition_to_ensures_previous_transition_is_first_completed_before_starting_subsequent_transition()
    {
        var factory = new StateMachineTaskFactory<State>();
        factory.RegisterTransition(State.Starting, State.Started, (ct, o) => TaskUtil.Delay(TimeSpan.FromMilliseconds(10)));
        factory.RegisterTransition(State.Stopping, State.Stopped, (ct, o) => TaskUtil.Delay(TimeSpan.FromMilliseconds(10)));

        var startedAt = DateTime.MinValue;
        var stoppedAt = DateTime.MinValue;
        var startedTask = factory.TransitionTo(State.Started).ContinueWith(x => startedAt = DateTime.UtcNow, TaskContinuationOptions.ExecuteSynchronously);
        var stoppedTask = factory.TransitionTo(State.Stopped).ContinueWith(x => stoppedAt = DateTime.UtcNow, TaskContinuationOptions.ExecuteSynchronously);

        Assert.True(Task.WaitAll(new Task[] { startedTask, stoppedTask }, TimeSpan.FromSeconds(3)), "Timed out waiting for tasks to complete.");
        Assert.True(stoppedAt > startedAt, "stoppedAt is " + stoppedAt.Millisecond + " and startedAt is " + startedAt.Millisecond + ", difference is " + (stoppedAt - startedAt).ToString());
    }

    [Fact]
    public void transition_to_can_be_canceled_before_transition_takes_place()
    {
        var factory = new StateMachineTaskFactory<State>();
        var cancellationTokenSource = new CancellationTokenSource();
        factory.RegisterTransition(State.Starting, State.Started, (ct, o) => TaskUtil.FromResult(true));

        cancellationTokenSource.Cancel();
        var startedTask = factory.TransitionTo(State.Started, cancellationTokenSource.Token);

        try
        {
            startedTask.Wait();
            Assert.True(false, "Failed to throw exception.");
        }
        catch (AggregateException ex)
        {
            Assert.Equal(1, ex.InnerExceptions.Count);
            Assert.IsType<OperationCanceledException>(ex.InnerExceptions[0]);
        }
    }

    [Fact]
    public void transition_to_can_be_canceled()
    {
        var factory = new StateMachineTaskFactory<State>();
        var cancellationTokenSource = new CancellationTokenSource();
        factory.RegisterTransition(State.Starting, State.Started, (ct, o) => TaskUtil.FromResult(true));
        factory.RegisterTransition(State.Stopping, State.Stopped, (ct, o) => TaskUtil.Delay(TimeSpan.FromMilliseconds(150)));

        var startedTask = factory.TransitionTo(State.Started, cancellationTokenSource.Token);
        startedTask.ContinueWith(x => cancellationTokenSource.Cancel());
        var stoppedTask = factory.TransitionTo(State.Stopped, cancellationTokenSource.Token);

        startedTask.Wait(TimeSpan.FromSeconds(3));

        try
        {
            stoppedTask.Wait(TimeSpan.FromSeconds(3));
            Assert.True(false, "Failed to throw exception.");
        }
        catch (AggregateException ex)
        {
            Assert.Equal(1, ex.InnerExceptions.Count);
            Assert.IsType<OperationCanceledException>(ex.InnerExceptions[0]);
        }
    }

    [Fact]
    public void transition_to_can_be_forbidden()
    {
        var factory = new StateMachineTaskFactory<State>();
        factory.RegisterTransition(State.Starting, State.Started, (ct, o) => TaskUtil.FromResult(true));
        factory.RegisterTransition(State.Stopping, State.Stopped, (ct, o) => TaskUtil.FromResult(true));

        var startedTask = factory.TransitionTo(State.Started, CancellationToken.None, x => x == State.Undefined);
        var stoppedTask = factory.TransitionTo(State.Stopped, CancellationToken.None, x => x != State.Started);

        startedTask.Wait(TimeSpan.FromSeconds(3));

        try
        {
            stoppedTask.Wait(TimeSpan.FromSeconds(3));
            Assert.True(false, "Failed to throw exception.");
        }
        catch (AggregateException ex)
        {
            Assert.Equal(1, ex.InnerExceptions.Count);
            var ex2 = Assert.IsType<StateTransitionForbiddenException<State>>(ex.InnerExceptions[0]);
            Assert.Equal(State.Stopped, ex2.TargetState);
            Assert.Equal(State.Started, ex2.State);
            Assert.Equal("A transition to state 'Stopped' was forbidden by the validate transition callback.", ex2.Message);
        }
    }

    [Fact]
    public void canceled_transition_reverts_back_to_original_state()
    {
        var factory = new StateMachineTaskFactory<State>();
        var cancellationTokenSource = new CancellationTokenSource();
        factory.RegisterTransition(State.Starting, State.Started, (ct, o) => TaskUtil.FromResult(true));
        factory.RegisterTransition(State.Stopping, State.Stopped, (ct, o) => TaskUtil.Delay(TimeSpan.FromSeconds(3), cancellationTokenSource.Token));

        factory.StateChanged += (s, e) =>
            {
                if (e.NewState == State.Stopping)
                {
                    // cancel the stop
                    cancellationTokenSource.Cancel();
                }
            };

        var startedTask = factory.TransitionTo(State.Started);
        var stoppedTask = factory.TransitionTo(State.Stopped, cancellationTokenSource.Token);

        startedTask.Wait(TimeSpan.FromSeconds(3));

        try
        {
            stoppedTask.Wait(TimeSpan.FromSeconds(3));
            Assert.True(false, "Failed to throw exception.");
        }
        catch (AggregateException ex)
        {
            Assert.Equal(1, ex.InnerExceptions.Count);
            Assert.IsType<OperationCanceledException>(ex.InnerExceptions[0]);
            Assert.Equal(State.Started, factory.State);
        }
    }

    [Fact]
    public void failed_transition_reverts_back_to_original_state()
    {
        var factory = new StateMachineTaskFactory<State>();
        factory.RegisterTransition(State.Starting, State.Started, (ct, o) => TaskUtil.FromResult(true));
        factory.RegisterTransition(State.Stopping, State.Stopped, (ct, o) => { throw new InvalidOperationException("Something went wrong"); });

        var startedTask = factory.TransitionTo(State.Started);
        var stoppedTask = factory.TransitionTo(State.Stopped);

        startedTask.Wait(TimeSpan.FromSeconds(3));

        try
        {
            stoppedTask.Wait(TimeSpan.FromSeconds(3));
            Assert.True(false, "Failed to throw exception.");
        }
        catch (AggregateException ex)
        {
            Assert.Equal(1, ex.InnerExceptions.Count);
            Assert.IsType<InvalidOperationException>(ex.InnerExceptions[0]);
            Assert.Equal(State.Started, factory.State);
        }
    }

    [Fact]
    public void state_change_is_raised_as_state_changes()
    {
        var factory = new StateMachineTaskFactory<State>(State.Stopped);
        factory.RegisterTransition(State.Starting, State.Started, (ct, o) => TaskUtil.FromResult(true));
        factory.RegisterTransition(State.Stopping, State.Stopped, (ct, o) => TaskUtil.FromResult(true));
        var stateChanges = new List<StateChangedEventArgs<State>>();
        factory.StateChanged += (s, e) => stateChanges.Add(e);

        factory.TransitionTo(State.Started).Wait(TimeSpan.FromSeconds(1));
        factory.TransitionTo(State.Stopped).Wait(TimeSpan.FromSeconds(1));
        factory.TransitionTo(State.Started).Wait(TimeSpan.FromSeconds(1));
        factory.TransitionTo(State.Stopped).Wait(TimeSpan.FromSeconds(1));

        Assert.Equal(8, stateChanges.Count);
        Assert.Equal(State.Stopped, stateChanges[0].OldState);
        Assert.Equal(State.Starting, stateChanges[0].NewState);
        Assert.Equal(State.Starting, stateChanges[1].OldState);
        Assert.Equal(State.Started, stateChanges[1].NewState);
        Assert.Equal(State.Started, stateChanges[2].OldState);
        Assert.Equal(State.Stopping, stateChanges[2].NewState);
        Assert.Equal(State.Stopping, stateChanges[3].OldState);
        Assert.Equal(State.Stopped, stateChanges[3].NewState);
        Assert.Equal(State.Stopped, stateChanges[4].OldState);
        Assert.Equal(State.Starting, stateChanges[4].NewState);
        Assert.Equal(State.Starting, stateChanges[5].OldState);
        Assert.Equal(State.Started, stateChanges[5].NewState);
        Assert.Equal(State.Started, stateChanges[6].OldState);
        Assert.Equal(State.Stopping, stateChanges[6].NewState);
        Assert.Equal(State.Stopping, stateChanges[7].OldState);
        Assert.Equal(State.Stopped, stateChanges[7].NewState);
    }

    [Fact]
    public void state_gets_the_current_state()
    {
        var factory = new StateMachineTaskFactory<State>(State.Stopped);
        factory.RegisterTransition(State.Starting, State.Started, (ct, o) => TaskUtil.Delay(TimeSpan.FromMilliseconds(100)));
        factory.RegisterTransition(State.Stopping, State.Stopped, (ct, o) => TaskUtil.Delay(TimeSpan.FromMilliseconds(100)));

        var task = factory.TransitionTo(State.Started);
        Assert.Equal(State.Starting, factory.State);
        task.Wait(TimeSpan.FromSeconds(3));
        Assert.Equal(State.Started, factory.State);
        task = factory.TransitionTo(State.Stopped);
        Assert.Equal(State.Stopping, factory.State);
        task.Wait(TimeSpan.FromSeconds(3));
        Assert.Equal(State.Stopped, factory.State);
    }
}
0
0

Likely not what you want, but if queuing them up instead of ignoring is the intent (or is acceptable), then one relatively simple option would be to use the limited-concurrency scheduler for those 2 StartNew calls.

It's more code than necessary to get the effect you're looking for, but would let you leverage something that's already written instead of writing your own code. :)

0
-1

Well, if you want only one instance of the class being active at a time you should consider use a Singleton Pattern.

I am not an expert in Patterns so if the solution I use always has a name, I don't know it. I do not use tasks but threads. Here is my code.

public class Service
{
    private object oLock;
    private bool running;
    private Thread threadTask;
    private AutoResetEvent taskStarted;

    public bool IsRunning { get { return this.running; } }

    public Service()
    {
        oLock = new object();
        taskStarted = new AutoResetEvent(false);
        running = false;
    }

    public void Start()
    {
        // If we can not acquire the lock, then there is a Start or Stop operation 
        // in progress, so better leave. Also leave if already running.
        if (running || !Monitor.TryEnter(oLock))
            return;

        // Set running flag to prevent other threads to start service again
        running = true;

        // Create and start the thread
        threadTask = new Thread(new ThreadStart(Task));
        threadTask.IsBackground = true;
        threadTask.Start();

        // Wait until the task execution begins. This is optional
        taskStarted.WaitOne();

        // Release the lock
        Monitor.PulseAll(oLock);
        Monitor.Exit(oLock);
    }

    public void Stop()
    {
        // If we can not acquire the lock, then there is a Start or Stop operation 
        // in progress, so better leave. Also leave if not running.
        if(!running || !Monitor.TryEnter(oLock))
            return;

        // Clear the running task to prevent reentrancy
        running = false;

        // Here we can abort the thread. This is optional an depends on task
        threadTask.Abort();

        // Wait until the thrad finish
        threadTask.Join();

        // Clear
        threadTask = null;

        // Release the lock
        Monitor.PulseAll(oLock);
        Monitor.Exit(oLock);
    }

    protected virtual void Task()
    {
        // Setup task and allocate resources
        taskStarted.Set();

        // Execute the task poll
        while (running)
        {
        }

        // Finish the task and release resources
    }
}

One of the tricks is the use of Monitor class instead of a lock statement, so the first thread that tries to start the service will win, and the other threads will for a service which is already started or stopping. Be carefull if you plan to invert the order of the

if (Monitor.TryEnter() || running)
    return;

you must call Monitor.Exit or your app will deadlock.

You can, of course, change the running boolean for an enum which represents the Idle, Starting, Running, and Stopping status.

Also its a good idea to make the class abstract and let inheriters to override the method to be called inside the/instead of the while statement.

Hope this helps. Best regards.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.