Last active
October 7, 2018 19:44
-
-
Save foobit/4824ad298669368b65568eb782a18780 to your computer and use it in GitHub Desktop.
Simple C# Task based state machine
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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