完成服务并停止线程

本文关键字:线程 服务 | 更新日期: 2023-09-27 18:04:37

我有几个服务,并使用线程来实现每个服务。服务按顺序执行。让我举一个例子来做演示。

            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()?

完成服务并停止线程

好吧,评论是误导。线程将休眠864毫秒,而不是24小时。

Thread.Sleep(864);// 24 hours.

如果你真的想在一个循环中休眠那么长时间,那么使用ManualResetEvent,这样你就可以在任何时候中止等待。

ManualResetEvent cancelEvent;
in loop:
 if(cancelEvent.WaitOne(TimeSpan.FromHours(24))){
    break;
 }
and, in Stop method:
 cancelEvent.Set();

也删除

if (this._isRunning)
{
    WriteLogInfo("Restarting thread due to failure...");
    try
    {
        Thread.CurrentThread.Start();
    }
    catch (Exception ex)
    {
        WriteLogError("Error restarting thread... " + ex.ToString());
    }
}

并且确保_isRunning是volatile,否则它可能会被缓存而不会在另一个线程中更新。当您调用Stop()时,服务将和平退出。