本文介绍了我如何安全地停止在Windows服务运行的C#.NET线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我保持一些code这看起来是这样的。这是一个Windows服务,做一些工作,每次30分钟。该ActualWorkDoneHere方法需要大约30秒的运行,但如果它运行时停止它可以留下的东西在一个糟糕的状态。什么是prevent这种情况发生的最好方法是什么?我应更换而(真)与被设置为false中的onStop方法(删除线程中止调用)一个布尔值?是否有某种方式来告诉我们,如果一个线程处于休眠状态?

 命名空间WorkService
{
    公共部分类WorkService:ServiceBase的
    {
        私人螺纹_workerThread = NULL;

        公共WorkService()
        {
            的InitializeComponent();
        }

        保护覆盖无效的OnStart(字串[] args)
        {
            _workerThread =新主题(新的ThreadStart(DoWork的));
            _workerThread.Start();
        }

        保护覆盖无效的onStop()
        {
            _workerThread.Abort();
        }

        静态无效的DoWork()
        {
            INT sleepMinutes = 30;

            而(真)
            {
                 ActualWorkDoneHere();

                 System.Threading.Thread.Sleep(新时间跨度(0,sleepMinutes,0));
            }
        }
    }
}
 

解决方案

当我有这样的事情,我通常会使用的ManualResetEvent 。这是设置在停止()通话。然后,我等待一个超时:

 为(;;)
{
    如果(_stop.WaitOne(超时))
        打破;
    做一点事();
}
 

I am maintaining some code which looks something like this. It's a Windows service which does some work every 30 minutes. The ActualWorkDoneHere method takes about 30 seconds to run, but if it is stopped while running it can leave things in a bad state. What is the best way to prevent that from happening? Should I replace the While(true) with a boolean which is set to false in the onstop method (removing the thread Abort call)? Is there some way to tell if a thread is sleeping?

namespace WorkService
{
    public partial class WorkService : ServiceBase
    {
        private Thread _workerThread = null;

        public WorkService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            _workerThread = new Thread(new ThreadStart(DoWork));
            _workerThread.Start();
        }

        protected override void OnStop()
        {
            _workerThread.Abort();
        }

        static void DoWork()
        {
            int sleepMinutes = 30;

            while (true)
            {
                 ActualWorkDoneHere();

                 System.Threading.Thread.Sleep(new TimeSpan(0, sleepMinutes, 0));
            }
        }
    }
}
解决方案

When I have something like this, I usually use a ManualResetEvent. This is set in the Stop() call. Then I wait with a timeout:

for (;;)
{
    if (_stop.WaitOne(timeout))
        break;
    DoSomething();
}

这篇关于我如何安全地停止在Windows服务运行的C#.NET线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 06:30