Hi guys,
I have a method that I would like to run over and over again.I would like to be able to start and stop this process.
I have been using this pattern for some socket work and I am wondering what improvements I can make?
public delegate void VoidMethod();
public class MethodLooper
{
private VoidMethod methodToLoop;
private volatile bool doMethod;
private readonly object locker = new object();
private readonly Thread loopingThread;
public void Start()
{
if (!doMethod)
{
doMethod = true;
loopingThread.Start();
}
}
public void Stop()
{
if (doMethod)
{
doMethod = false;
loopingThread.Join();
}
}
public void ChangeMethod(VoidMethod voidMethod)
{
if (voidMethod == null)
throw new NullReferenceException("voidMethod can't be a null");
Stop();
lock (locker)
{
methodToLoop = voidMethod;
}
}
public MethodLooper(VoidMethod voidMethod)
{
if (voidMethod == null)
throw new NullReferenceException("voidMethod can't be a null");
methodToLoop = voidMethod;
loopingThread = new Thread(new ThreadStart(_MethodLoop));
}
private void _MethodLoop()
{
VoidMethod methodToLoopCopy;
while (doMethod)
{
lock (methodToLoop)
{
methodToLoopCopy = methodToLoop;
}
methodToLoopCopy();
}
}
}