我有一個方法,我想一遍又一遍地運行。c#方法循環和控制
我一直在使用這種模式的一些插座工作,我想知道我可以做什麼改進?
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();
}
}
}
對不起!錯誤修正abelenky - 即時累了 - 現在穩定與獵戶座建議的一些功能 – divinci 2009-05-31 02:07:32