谁能告诉我如何从 Windows 服务(在 C# 中)运行长时间运行的进程?该过程可能需要数小时才能完成。该服务应检查数据库中是否有待执行的作业。每项工作可能需要很长时间才能完成。如果没有挂起的作业,那么它应该休眠 2 分钟(可配置),然后重新开始。我如何使用 Windows 服务执行此操作?提前致谢。
最佳答案
你必须像这样创建控制台应用程序
static void Main(string[] args)
{
bool createdNew;
Mutex m = new Mutex(true, "YourBatchProcessor", out createdNew);
if (!createdNew)
{
Console.WriteLine("YourBatchProcesso is already running!");
return;
}
//your code goes here
}
正如 Gmoliv 所说,创建计划任务而不是每 2 分钟运行一次
或者如果你想写窗口服务那么你的服务代码就像
public class YourServrClass
{
private int numticks = 0;
private Timer _timer;
private bool _IsStarted;
private int Interval =2000; //ticks //2 sec.
#region Initializer
public YourServrClass()
{
InitializeComponent();
_timer = new Timer();
_timer.Interval = Interval;
_timer.Elapsed += new ElapsedEventHandler(this.Timer_Tick);
}
#endregion
#region Timer_Tick to process
private void Timer_Tick(object sender, System.Timers.ElapsedEventArgs e)
{
numticks++;
if (_IsStarted)
{
_timer.Stop();
//your code //ProcessYourData();
_timer.Start();
}
}
#endregion
protected override void OnStart(string[] args)
{
_IsStarted=true;
}
protected override void OnStop()
{
_IsStarted=false;
}
}
关于c# - 如何在 Windows 服务中运行长时间运行的进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3891684/