【发布时间】: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