【发布时间】:2021-02-08 13:50:30
【问题描述】:
我想用 C# 构建一个 Windows 服务。
此服务需要每隔 10 秒定期运行一次。
问题:
-
Timers.timer 和 Threading.timer 有什么区别?
-
如何调用带参数的 CheckingThings?
-
如果我运行此代码,它会像此处声明的那样每秒多次调用 CheckingThings:
_timer = new Timer(new TimerCallback(CheckingThings), autoEvent, 5000, 1000);
这是我目前得到的:
public partial class WindowsService1 : ServiceBase
{
// Logging
private static Serilog.Core.Logger _logEvent;
public WindowsService1()
{
InitializeComponent();
}
public void OnDebug() {
OnStart(null);
}
protected override void OnStart(string[] args)
{
//Logging
try {
_logEvent = new LoggerConfiguration()
.WriteTo.File(AppDomain.CurrentDomain.BaseDirectory + @"Logs\Logfile.txt", rollingInterval: RollingInterval.Month)
.CreateLogger();
}
catch (Exception e)
{
_logEvent.Error("The logging service is not working as expected: {errorMsg}", e);
}
try
{
// initializing some data here
var autoEvent = new AutoResetEvent(true);
while (true)
{
_timer = new Timer(new TimerCallback(CheckingThings), autoEvent, 5000, 1000);
}
}
catch (Exception e) {
_logEvent.Error("An error occured while initializing service: {0}", e);
}
}
private static void CheckingThings(object stateInfo)
AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
//These things needs to run periodically every 10s
}
protected override void OnStop()
{
_logEvent.Information("Stopping Service ...");
}
}
【问题讨论】:
-
您的第一个问题已经在这里得到解答:stackoverflow.com/questions/1416803/…
-
你似乎创建了无限数量的计时器
while (true) _timer = new Timer(new TimerCallback(CheckingThings), autoEvent, 5000, 1000); -
如果我删除 while 循环它只运行一次
-
您想构建 Windows 服务还是定期运行它?
-
我如何使用参数调用 CheckingThings? - 如果您对计时器说“这里,每 10 秒调用一次此方法并提供各种参数”,您如何期待计时器知道要提供哪些参数?您如何期望手机的早上 8 点闹钟会打开您的咖啡机?您希望它如何拨入您上午 10 点会议的会议号码和 PIN 码? (提示;它不会 - 它只是提醒您当前时间,因此您必须执行这些操作)
标签: c# multithreading service task