gpt4 book ai didi

c# - Windows服务计时器多线程

转载 作者:行者123 更新时间:2023-12-03 13:21:54 25 4
gpt4 key购买 nike

我正在构建Windows服务,该服务将基于数据库中的计划审核用户。该服务每十分钟检查一次数据库,以进行计划的审核。一旦审计开始,它将在数据库表中标记一个开始时间,因此如果花费的时间超过十分钟,它将不会再次开始。

我的问题是,下面的代码是否可以接受我的工作,并且每隔10分钟我应该使用多线程吗?如果是,我将如何完成此工作?

我的示例代码:

protected override void OnStart(string[] args)
{
var aTimer = new Timer(600000);
aTimer.Elapsed += ATimerElapsed;
aTimer.Interval = 600000;
aTimer.Enabled = true;
GC.KeepAlive(aTimer);
}

private static void ATimerElapsed(object sender, ElapsedEventArgs e)
{
try
{
Worker.ProcessScheduledAudits();
}
catch (Exception ex)
{
EventLog.WriteEntry("Application", ex.Message, EventLogEntryType.Error);
}
}

最佳答案

System.Threading.Timer将使用Threadpool中的线程来运行Elapsed处理程序。因此,您仅通过使用计时器就已经在使用多线程。实际上,所有计时器都使用某种类型的后台线程。它们只是在多线程的方式上有所不同,以便针对预期用途进行最有意义的操作。

如果您需要每十分钟运行一次,但又要确保两个处理程序永远不会同时运行,请尝试在Elapsed方法中设置一个“CurrentlyRunning”标志,并在进行任何繁重的操作之前对其进行检查。

    protected override void OnStart(string[] args)
{
var aTimer = new Timer(600000);
aTimer.Elapsed += ATimerElapsed;
aTimer.Interval = 600000;
aTimer.Enabled = true;
GC.KeepAlive(aTimer);
}

private static currentlyRunning;

private static void ATimerElapsed(object sender, ElapsedEventArgs e)
{
if(currentlyRunning) return;
currentlyRunning = true;
try
{
Worker.ProcessScheduledAudits();
}
catch (Exception ex)
{
EventLog.WriteEntry("Application", ex.Message, EventLogEntryType.Error);
}
currentlyRunning = false;
}

从理论上讲,这可能会竞赛,但是由于您仅每10分钟就为此事件启动一个线程,因此可能性极小。

关于c# - Windows服务计时器多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6335431/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com