在定期处理中使用膨胀线程的问题

时间:2013-06-13 16:32:04

标签: c# multithreading task-parallel-library periodic-processing

我想在工作线程上做一些定期工作,它会在工作完成时发出信号。当发出信号时,我想等待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后线程不会死?我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

未经测试,但我认为这是因为事件没有重置

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

此外,我不明白为什么你这样做,你不能使用计时器,这是为这种用例精确设计的吗?