完成服务并停止线程

时间:2013-03-18 18:10:20

标签: c#

我有几个服务并使用线程来实现每个服务。服务按顺序执行。我只需拿起一个用于演示目的。

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

1 个答案:

答案 0 :(得分:0)

好吧,评论有误导性。线程将睡眠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是易失性的,否则它可能会被缓存而不会在另一个线程中更新。当你拨打Stop()时,你的服务会安静地退出。