Created
November 26, 2013 18:11
-
-
Save davidwhitney/7663120 to your computer and use it in GitHub Desktop.
Engine block
This file contains hidden or 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
public class Engine<T> where T: IEngineComponent | |
{ | |
private readonly T _component; | |
protected bool ContinueLooping; | |
private Thread _thread; | |
public Engine(T component) | |
{ | |
_component = component; | |
} | |
~Engine() | |
{ | |
Stop(); | |
TerminateThread(); | |
} | |
public void Start(ThreadPriority priority = ThreadPriority.Normal) | |
{ | |
PreStart(); | |
ContinueLooping = true; | |
_thread = new Thread(ThreadedTask) { Name = typeof(T).Name, Priority = priority }; | |
_thread.Start(); | |
} | |
public void Stop() | |
{ | |
PreStop(); | |
ContinueLooping = false; | |
} | |
public virtual void PreStart() { } | |
public virtual void PreStop() { } | |
private void ThreadedTask() | |
{ | |
while (ContinueLooping) | |
{ | |
_component.Step(); | |
Thread.Sleep(_component.IntervalMs); | |
} | |
} | |
private void TerminateThread() | |
{ | |
if (_thread == null || !_thread.IsAlive) | |
{ | |
return; | |
} | |
if (!_thread.Join(2000)) | |
{ | |
_thread.Abort(); | |
} | |
} | |
} | |
public interface IEngineComponent | |
{ | |
int IntervalMs { get; set; } | |
void Step(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment