【问题标题】:Check thread status in Parallel.foreach to exit when Onstop() is called检查 Parallel.foreach 中的线程状态以在调用 Onstop() 时退出
【发布时间】:2018-04-14 06:43:00
【问题描述】:

我有一个 Windows 服务,它在 foreach 中并行执行某些操作。我不希望并行 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
      //...
    });
}

【问题讨论】:

  • 您的基本问题可能是 Timer 而不是 ForEach()。我不完全确定它现在在哪个线程上执行。您可以在循环之前检查Thread.CurrentThread.IsBackground。

标签: c# .net multithreading windows-services parallel.foreach


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多