0

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

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

4

1 回答 1

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 是 volatile 的,否则它可能会被缓存而不会在另一个线程中更新。当您调用 Stop() 时,您的服务将和平退出。

于 2013-03-18T18:15:12.670 回答