gpt4 book ai didi

c# - 如何为共享主机上的 MVC 应用程序正确运行后台线程?

转载 作者:行者123 更新时间:2023-11-30 14:29:11 26 4
gpt4 key购买 nike

我需要为我的 MVC 4 应用程序运行后台线程,该线程大约每隔一小时唤醒一次,以删除数据库中的旧文件,然后返回休眠状态。此方法如下:

//delete old files from database
public void CleanDB()
{
while (true)
{
using (UserZipDBContext db = new UserZipDBContext())
{
//delete old files
DateTime timePoint = DateTime.Now.AddHours(-24);
foreach (UserZip file in db.UserFiles.Where(f => f.UploadTime < timePoint))
{
db.UserFiles.Remove(file);
}
db.SaveChanges();
}
//sleep for 1 hour
Thread.Sleep(new TimeSpan(1, 0, 0));
}
}

但是我应该从哪里开始这个线程呢? this question中的答案创建一个新线程并在 Global.asax 中启动它,但这篇文章还提到“ASP.NET 不是为长时间运行的任务设计的”。我的应用程序将在我没有管理员权限的共享主机上运行,​​因此我认为我无法为此任务安装单独的程序。

简而言之,

  1. 鉴于我的线程不做太多事情(大部分时间都在休眠和小数据库),是否可以在 Global.asax 中启动线程?

  2. 我了解到这种方法的风险是线程可能会被终止(虽然不确定原因)。我如何检测线程何时被终止以及我能做什么?

  3. 如果这是一个非常糟糕的主意,我还能在共享主机上做些什么?

谢谢!

更新

@usr提到Application_Start中的方法可以多次调用,建议使用Lazy。在我阅读该主题之前,我想到了这种方法。多次调用 SimplePrint.startSingletonThread() 只会实例化一个线程(我认为)。对吗?

public class SimplePrint
{
private static Thread tInstance = null;

private SimplePrint()
{
}

public static void startSingletonThread()
{
if (tInstance == null)
{
tInstance = new Thread(new ThreadStart(new SimplePrint().printstuff));
tInstance.Start();
}
}

private void printstuff()
{
DateTime d = DateTime.Now;
while (true)
{
Console.WriteLine("thread started at " + d);
Thread.Sleep(2000);
}
}
}

最佳答案

我认为你应该尝试 Hangfire .

Incredibly easy way to perform fire-and-forget, delayed and recurring tasks inside ASP.NET applications. No Windows Service required.

Backed by Redis, SQL Server, SQL Azure, MSMQ, RabbitMQ.

因此您不需要管理员权限。

RecurringJob.AddOrUpdate(
() =>
{
using (UserZipDBContext db = new UserZipDBContext())
{
//delete old files
DateTime timePoint = DateTime.Now.AddHours(-24);
foreach (UserZip file in db.UserFiles.Where(f => f.UploadTime < timePoint))
{
db.UserFiles.Remove(file);
}
db.SaveChanges();
}
}
Cron.Hourly);

关于c# - 如何为共享主机上的 MVC 应用程序正确运行后台线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27012947/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com