Skip to content

Instantly share code, notes, and snippets.

@davidwhitney
Created November 26, 2013 18:11
Show Gist options
  • Save davidwhitney/7663120 to your computer and use it in GitHub Desktop.
Save davidwhitney/7663120 to your computer and use it in GitHub Desktop.
Engine block
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