gpt4 book ai didi

c# - System.threading.timer 在 Windows 服务中不工作

转载 作者:太空狗 更新时间:2023-10-30 00:03:34 34 4
gpt4 key购买 nike

我在 Windows 服务中使用 System.threading.timer。但是定时器没有成功执行。下面是代码。

    protected override void OnStart(string[] args)
{
try
{
eventLog1.WriteEntry("In OnStart");
TimeSpan dueMinutes = TimeSpan.FromMinutes(1);
TimeSpan fromMinutes = TimeSpan.FromMinutes(1);
System.Threading.Timer timer = new System.Threading.Timer(new TimerCallback(CallBack), null, dueMinutes, fromMinutes);


/*
System.Timers.Timer timer = new System.Timers.Timer(5 * 60 * 1000);
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
DBSyncHandler sync = new DBSyncHandler();
sync.startSync();
*/
}
catch (Exception ex)
{
if (!System.Diagnostics.EventLog.SourceExists("MySource"))
{
System.Diagnostics.EventLog.CreateEventSource("MySource", "MyEventLog");
}
eventLog1.Source = "MySource";
eventLog1.Log = "MyEventLog";
eventLog1.WriteEntry("Error : " + ex.Message);
}

}



public static void CallBack(object sender)
{

try
{
DBSyncHandler sync = new DBSyncHandler();
sync.startSync();
}
catch (Exception ex)
{
EventLog eventLog1 = new EventLog();
if (!System.Diagnostics.EventLog.SourceExists("MySource"))
{
System.Diagnostics.EventLog.CreateEventSource("MySource", "MyEventLog");
}
eventLog1.Source = "MySource";
eventLog1.Log = "MyEventLog";
eventLog1.WriteEntry("Error : " + ex.Message);
}

}

安装成功后。我的工作站重新启动。重新启动机器时,服务被成功调用。但是一旦第一次调用服务,它不会在下一次持续时间内重复,即不会再次调用服务。

最佳答案

阅读 MSDN 上的注释:http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx

As long as you are using a Timer, you must keep a reference to it. As with any managed object, a Timer is subject to garbage collection when there are no references to it. The fact that a Timer is still active does not prevent it from being collected.

System.Threading.Timer is a simple, lightweight timer that uses callback methods and is served by thread pool threads. It is not recommended for use with Windows Forms, because its callbacks do not occur on the user interface thread. System.Windows.Forms.Timer is a better choice for use with Windows Forms. For server-based timer functionality, you might consider using System.Timers.Timer, which raises events and has additional features.

我认为您在 OnStart 中创建的计时器对象被 gc 收集或处置。它不应该是该方法中的局部变量,因为它超出了范围。

关于c# - System.threading.timer 在 Windows 服务中不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7513347/

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