我已经使用 Timer.Elapsed 事件实现了以下代码,该事件运行批处理并截取我的桌面的屏幕截图。除了 ElapsedHandler 之外,批处理过程在代码中的其他任何地方都可以完美运行。我知道处理程序被正确调用,因为我添加了一些代码来打印到文件中,它运行良好。然而,批处理本身永远不会被执行。我是否遗漏了导致问题的计时器的某些内容?
using System;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Timers;
using System.Drawing;
using System.Drawing.Imaging;
using System.ServiceProcess;
namespace ScreenCaptureService
{
public class ScreenCaptureService : ServiceBase
{
private const int durationInMinutes = 1;
private System.Timers.Timer t;
protected override void OnStart(string[] args)
{
t = new System.Timers.Timer((float)(1000));
t.Elapsed += new ElapsedEventHandler(ElapsedHandler);
t.Enabled = true;
}
protected void ElapsedHandler(object sender, ElapsedEventArgs e)
{
string testpath = @"C:\Dump\new.txt";
if (!File.Exists(testpath))
{
File.CreateText(testpath);
using (StreamWriter sw = File.AppendText(testpath))
{
sw.WriteLine("Initialized");
}
}
else
{
using (StreamWriter sw = File.AppendText(testpath))
{
sw.WriteLine("Hello " + DateTime.Now.ToString());
}
}
Process.Start(@"C:\users\wyoung\screenshot.bat");
}
protected override void OnStop()
{
t.Enabled = false;
}
}
}