void worker_DoWork(object sender, DoWorkEventArgs e) { lock (Brains) { // Sort the List, States may have updated Priorities. Brains.Sort(); // Find a State that says it needs to run. foreach (BaseState BS in Brains) { // Cancel operations if pause pending. if (worker.CancellationPending) { e.Cancel = true; return; } if (BS.Enabled == false) { continue; } // Skip disabled States. if (BS.CheckState() == true) { // Says it needs to run. Same State as before? if (LastRan == null) { LastRan = BS; } if (LastRan != BS) { // Make the previous State clean up and exit. LastRan.ExitState(); LastRan = BS; BS.EnterState(); } // Run this State and stop. BS.RunState(); } } } }