gpt4 book ai didi

c# - ASP webapp 中的后台任务

转载 作者:太空狗 更新时间:2023-10-29 21:41:35 26 4
gpt4 key购买 nike

我是 C# 的新手,最近使用 .NET 4.0 构建了一个小型网络应用程序。这个应用程序有 2 个部分:一个设计为永久运行,并将持续从网络上的给定资源中获取数据。另一个根据请求访问该数据以对其进行分析。我正在为第一部分而苦苦挣扎。

我最初的方法是设置一个 Timer 对象,该对象每隔 5 分钟执行一次提取操作(无论该操作在这里并不重要)。我会在 Application_Start 上定义该计时器,然后让它继续运行。

但是,我最近意识到应用程序是根据用户请求创建/销毁的(根据我的观察,它们似乎会在一段时间不活动后被销毁)。因此,我的后台事件将停止/恢复,超出我的控制,我希望它连续运行,绝对不会中断。

那么我的问题来了:这可以在网络应用中实现吗?还是我绝对需要一个单独的 Windows 服务来处理这类事情?

在此先感谢您的宝贵帮助!

纪尧姆

最佳答案

虽然在 Web 应用程序上执行此操作并不理想..这是可以实现的,因为网站始终处于运行状态。

这是一个示例:我在 global.asax 中创建一个过期的缓存项。当它过期时,将触发一个事件。您可以在 OnRemove() 事件中获取数据或任何内容。

然后您可以设置对页面(最好是非常小的页面)的调用,该页面将触发 Application_BeginRequest 中的代码,该代码将添加回缓存项并过期。

全局.asax:

private const string VendorNotificationCacheKey = "VendorNotification";
private const int IntervalInMinutes = 60; //Expires after X minutes & runs tasks

protected void Application_Start(object sender, EventArgs e)
{

//Set value in cache with expiration time
CacheItemRemovedCallback callback = OnRemove;

Context.Cache.Add(VendorNotificationCacheKey, DateTime.Now, null, DateTime.Now.AddMinutes(IntervalInMinutes), TimeSpan.Zero,
CacheItemPriority.Normal, callback);
}

private void OnRemove(string key, object value, CacheItemRemovedReason reason)
{
SendVendorNotification();

//Need Access to HTTPContext so cache can be re-added, so let's call a page. Application_BeginRequest will re-add the cache.
var siteUrl = ConfigurationManager.AppSettings.Get("SiteUrl");
var client = new WebClient();
client.DownloadData(siteUrl + "default.aspx");
client.Dispose();

}

private void SendVendorNotification()
{
//Do Tasks here
}

protected void Application_BeginRequest(object sender, EventArgs e)
{
//Re-add if it doesn't exist
if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("default.aspx") &&
HttpContext.Current.Cache[VendorNotificationCacheKey] == null)
{
//ReAdd
CacheItemRemovedCallback callback = OnRemove;
Context.Cache.Add(VendorNotificationCacheKey, DateTime.Now, null, DateTime.Now.AddMinutes(IntervalInMinutes), TimeSpan.Zero,
CacheItemPriority.Normal, callback);
}
}

如果您的计划任务很快,这很有效。如果这是一个长时间运行的过程..你肯定需要将它从你的网络应用程序中移除。

只要第一个请求启动了应用程序...即使站点上没有访问者,它也会每 60 分钟触发一次。

关于c# - ASP webapp 中的后台任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6418731/

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