我有几个服务并使用线程来实现每一个。服务按顺序执行。让我拿起一个用于演示目的。
services[1] = new RProcessing() { ConsoleInfoColor = ConsoleColor.Cyan };
success = services[1].Start();
if (success)
{
OutputUtils.WriteLogInfo("Service " + services[1].Name + " started...");
}
else
{
OutputUtils.WriteLogInfo("Service " + services[1].Name + " failed to start...");
previousStartup = false;
services[0].Stop();
}
内部 RProcessing。
public RProcessing()
{
worker = new Thread[1]; // Only one thread
for (int i = 0; i < 1; i++)
{
worker[i] = new Thread(new ThreadStart(ServiceLoop));
worker[i].Name = "R Thread_" + i.ToString();
}
// processing
}
public bool Start()
{
foreach (Thread t in worker)
t.Start();
return (true);
}
public bool Stop()
{
if (_isRunning)
{
_isRunning = false;
}
_isRunning = false;
base.Dispose();
WriteLogInfo("Shutdown of R Processor complete");
return (true);
}
public void ServiceLoop()
{
_isRunning = true;
WriteLogInfo("Starting ServiceLoop() for: " + Assembly.GetAssembly(typeof(RProcessing)).FullName);
string s;
while (_isRunning)
{
Thread.Sleep(500);
s = null;
try
{
WriteLogInfo(" processing "+s);
Thread.Sleep(864);// 24 hours.
}
catch (Exception ex)
{
WriteLogError("Thread " + Thread.CurrentThread.Name + " " + ex.ToString());
}
}
if (this._isRunning)
{
WriteLogInfo("Restarting thread due to failure...");
try
{
Thread.CurrentThread.Start();
}
catch (Exception ex)
{
WriteLogError("Error restarting thread... " + ex.ToString());
}
}
}
只有一个线程,我想完成它然后返回下一个服务。但是它总是在 ServiceLoop 中。怎么能破呢?只需调用 Stop()?