Skip to content

Instantly share code, notes, and snippets.

@foobit
Last active October 7, 2018 19:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save foobit/4824ad298669368b65568eb782a18780 to your computer and use it in GitHub Desktop.
Save foobit/4824ad298669368b65568eb782a18780 to your computer and use it in GitHub Desktop.
Simple C# Task based state machine
using System;
using System.Threading.Tasks;
public interface IState
{
Task RunAsync();
}
public class StateMachine
{
private Task currentTask = Task.CompletedTask;
public void SetState<T>() where T : IState, new()
{
Task.Run(() =>
{
currentTask.ContinueWith(_ => currentTask = new T().RunAsync() );
}).FireAndForget();
}
}
public static class TaskExtensions
{
public static void FireAndForget(this Task task) => task?.ContinueWith(t => GC.KeepAlive(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment