2

我想在工作完成时发出信号的工作线程上做一些定期工作。收到信号后,我想等待 5 秒钟,然后重新开始工作。我写了以下代码:

public class WinService : ServiceBase
{
    private readonly ManualResetEvent stopPeriodicProcess = new ManualResetEvent(false);

    protected override void OnStart(string[] args)
    {
        stopPeriodicProcess.Reset();
        ThreadPool.RegisterWaitForSingleObject(stopPeriodicProcess, InitializeEngines, null,5000, true);          
    }

    public void InitializeEngines(object state, bool timedOut)
    {       
        engine.LoadSettings();

        Task.Factory.StartNew(engine.DoSomeWork); //Fire and forget     
    }

    private void WorkCompletedEventHandler(object sender, WorkCompletedEventArgs e)
    {
        ThreadPool.RegisterWaitForSingleObject(stopPeriodicProcess,
                                               (state, timedOut) => DoPeriodicProcess(state, timedOut, e.EngineId), null,
                                               5000, true);
    }

    public void DoPeriodicProcess(object state, bool timedOut, string engineId)
    {
        if (timedOut)
        {                
            Task.Factory.StartNew(engine.DoSomeWork); //Fire and forget
        }
    }
}


public class Engine
{
    public event EventHandler<WorkCompletedEventArgs> WorkCompleted;    
    public void DoSomeWork()
    {
        //Doing some work..

        //Raise an event to signal that the work has been completed
        var args = new WorkCompletedEventArgs {EngineId = Settings.EngineId};
        RaiseWorkCompletedEvent(args);
    }

    protected virtual void RaiseWorkCompletedEvent(WorkCompletedEventArgs e)
    {
        EventHandler<WorkCompletedEventArgs> handler = WorkCompleted;
        if (handler != null)
        {
            handler(this, e);
        }
    }   
}

当我运行代码时,几秒钟后 CPU 使用率显示为 100%。在 VS 中调试时,我看到有太多活动的工作线程在WorkCompletedEventHandler内的RegisterWaitForSingleObject处等待。

为什么调用 RegisterWaitForSingleObject 后线程没有死掉?我错过了什么吗?

4

1 回答 1

0

Not tested but I think this is due to the event not being reset:

private void WorkCompletedEventHandler(object sender, WorkCompletedEventArgs e)
{
    stopPeriodicProcess.Reset();
    ThreadPool.RegisterWaitForSingleObject(stopPeriodicProcess,
                                           (state, timedOut) => DoPeriodicProcess(state, timedOut, e.EngineId), null,
                                           5000, true);
}

Moreover I don't understand why you're doing things this way, can't you use a timer, which is precisely designed for this kind of use-case?

于 2013-06-13T17:18:01.347 回答