我如何安全地停止在Windows服务运行的C#.NET线程?线程、安全、Windows、NET

2023-09-04 22:31:15 作者:淡漠安然

我保持一些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(超时))
        打破;
    做一点事();
}
 
不能访问windows installer服务,可能是你在安全模式下运行windows或者windows ins

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();
}

 
精彩推荐