检查 Parallel.foreach 中的线程状态,以便在调用 Onstop() 时退出



我有一个Windows服务,它并行执行某些操作。我不希望并行 foreach 在调用 onStop(( 方法时突然停止,而是等到并行的所有线程 foreach 完成其操作,然后服务必须停止。不确定如何做到这一点。请在下面找到我的示例代码:提前感谢..

//Initialize the timer
Timer timer = new Timer();
public ScheduledService()
{
    InitializeComponent();
}
protected override void OnStart(string[] args)
{
    //handle Elapsed event
    timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
    timer.Interval = 60000;
    timer.Enabled = true;
}
protected override void OnStop()
{
    timer.Enabled = false;    
    // wait till parallel foreach in processItem completes and then the stop
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
    ProcessItems();
}
private void ProcessItems()
{
    Parallel.ForEach(dt.AsEnumerable(), drow =>
    {
      //...
      // Do Stuff
      //...
    });
}

我要做的是在调用 OnStop(( 时设置一个标志(如果需要(,然后在并行循环语句之后编写代码以停止服务。