【发布时间】:2016-07-10 13:16:29
【问题描述】:
我创建了一个 asp.net mvc 项目。在这个项目中,我希望一些代码始终运行。我在网络托管服务上发布我的代码。我第一次通过向我的域发送 http 请求来启动应用程序,我希望应用程序始终保持活动状态并且永远不会关闭。但这不会发生。
即使我看到了一些解决方案,如果我有时在我的代码中 ping 我的域会阻止应用程序关闭。但是这个解决方案将应用程序生命周期延长到大约 24 小时(并非总是如此!!!)
这是我的代码:
public class Main
{
public static void main()
{
while (true)
{
try
{
// some codes
}catch(Exception exp)
{
// log the exception message, (but any exception hasn't occurred till now
}
}
}
}
Global.asax:(通过使用此代码,应用程序很快关闭,这样我使用了一个虚拟控制器)
public class MvcApplication : System.Web.HttpApplication
{
static Thread keepAliveThread = new Thread(KeepAlive);
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
keepAliveThread.Start();
Main.main();
}
protected void Application_End()
{
keepAliveThread.Abort();
}
static void KeepAlive()
{
while (true)
{
WebRequest req = WebRequest.Create("http://mydomain/Home/Index");
req.GetResponse();
try
{
Thread.Sleep(60000);
}
catch (ThreadAbortException)
{
break;
}
}
}
}
Global.asax:(通过使用此代码,应用程序保持运行大约 24 小时。这样我不使用任何控制器)
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
Main.main();
Timer timer = new Timer(new TimerCallback(refreshSession));
timer.Change(0, 5 * 60 * 1000); // 5 min
}
static void refreshSession(object state)
{
Unirest.get("http://mydomain/");
}
}
对于我的目的,有没有更好的解决方案?如果是,请给我一个示例代码。
【问题讨论】:
-
如果您可以访问iis配置,您可以将应用程序池启动模式更改为始终运行。
-
不,我没有访问它,我提到我在托管服务上发布我的应用程序
标签: asp.net-mvc session-timeout