简体   繁体   中英

Check thread status in Parallel.foreach to exit when Onstop() is called

I have an windows service which performs certain operation in parallel foreach. I don't want the parallel foreach to stop abruptly when onStop() method is called instead it has wait until all the threads in parallel foreach completes its operation and then service must stop. Not Sure on how to do this. Please find my sample code which I have below: Thanks in advance..

//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()时设置一个标志(如果需要),然后在并行循环语句之后编写代码以停止服务。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM