C# MVC5-Ninject-Tasks线程运行异常
我有一个线程,可以在特定时间拍摄事件以运行程序 我确实希望网站能够完全控制这个过程,所以我把它作为一个长期的循环线程构建到网站中 问题是我安排了一个任务在某个特定的时间发生,而它几乎是随机发生的(可能是在我加载页面时)。似乎web应用程序在使用之前会休眠所有线程 代码如下:C# MVC5-Ninject-Tasks线程运行异常,c#,asp.net-mvc,ninject,C#,Asp.net Mvc,Ninject,我有一个线程,可以在特定时间拍摄事件以运行程序 我确实希望网站能够完全控制这个过程,所以我把它作为一个长期的循环线程构建到网站中 问题是我安排了一个任务在某个特定的时间发生,而它几乎是随机发生的(可能是在我加载页面时)。似乎web应用程序在使用之前会休眠所有线程 代码如下: public void run() { Task.Factory.StartNew(() => { while (true) {
public void run()
{
Task.Factory.StartNew(() =>
{
while (true)
{
var lastDate = InternalEventLogger.GetLastDateTime();
if (DateTime.Now >= lastDate.AddDays(1))
{
System.Diagnostics.Debug.WriteLine(DateTime.Now);
System.Diagnostics.Debug.WriteLine(lastDate.AddDays(1));
InternalEventLogger.RefreshLog();
}
bool needUpdate = false;
System.Diagnostics.Debug.WriteLine("this");
List<Event> tempList = new List<Event>(this.evtList.getList());
foreach (Event evt in this.evtList.getList())
{
if (!evt.status.Equals("success"))
continue;
if (evt.nextRun <= DateTime.Now)
{
var tempEvt = evt;
System.Diagnostics.Debug.WriteLine("time to run: "+evt.name);
tempList.Remove(evt);
tempEvt.nextRun = evt.nextRun.AddMinutes(evt.interval);
tempEvt.lastRan = DateTime.Now;
tempList.Add(tempEvt);
needUpdate = true;
if (tempEvt.runLocation != null)
Task.Factory.StartNew(() =>
{
Process p = new Process();
p.StartInfo.FileName = tempEvt.runLocation;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.Start();
string output = p.StandardOutput.ReadToEnd();
string err = p.StandardError.ReadToEnd();
InternalEventLogger.WriteLog(output);
InternalEventLogger.WriteLog("// ------------- ERROR -------------- \n" + err);
p.WaitForExit();
});
}
}
if (needUpdate)
{
this.evtList.setList(tempList);
this.evtList.serialize(ConfigurationManager.AppSettings["xmlEventLocation"]);
}
Thread.Sleep(10000);
}
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
下面是一张显示计时问题的图片:
更新
已尝试以下设置,但仍无法正常工作
只有在访问时才会启动任务
您的IIS web服务器设置可能有问题。IIS应用程序池具有参数(在高级设置中):空闲超时(分钟)。默认情况下,此设置为20分钟。所以,当在20分钟内并没有对web站点的查询时,web服务器会停止应用程序池进程 参数解释。
需要更改IIS上循环计时器设置的链接 嗯。问题不在应用程序池空闲超时。另一个建议是:任务代码中可能会出现一些异常。使用try-catch和log-exception来解决问题。这不是因为,它在我访问站点后运行正常。您是否在Task.Factory.StartNew中捕获异常?我的意思是
Task.Factory.StartNew(()=>{try{…}catch(Exception ex){[log it here]}})
private static void RegisterServices(IKernel kernel)
{
evtManager = new EventManager(ConfigurationManager.AppSettings["xmlEventLocation"]);
evtManager.run();
// Initalize Event Logger
new InternalEventLogger();
}