我在Global.asax上有以下代码。它通常会生成电子邮件警报。我的问题是我已经设置每24小时发送一封电子邮件,但代码每10分钟发送一次电子邮件。我已经设定了:
HttpContext.Current.Cache.Add(CacheItemKey, "Test", null,
DateTime.MaxValue, TimeSpan.FromHours(24)
但应用程序每10分钟发送一次电子邮件。我也尝试了几分钟。
我的代码:
private const string CacheItemKey = "CacheFromMe";
public void CacheIRemovedCallback(string key,
object value, CacheItemRemoved reason)
{
HitmyPage();
// Do the service works
DosomeWork();
}
private const string myPageUrl = "myurl.aspx";
private void HitmyPage()
{
WebClient myclient = new WebClient();
myclient.DownloadData(myPageUrl);
}
protected void Application_BegintheRequests(Object sender, EventArgs e)
{
// If the dummy page is hit, then it means we want to add another item
// in cache
if (HttpContext.Current.Request.Url.ToString() == myPageUrl)
{
// Add the item in cache and when succesful, do the work.
RegistermyCacheEntries();
}
}
private void DosomeWork()
{
DoEmailStuff();
AnotherEmailStuff();
}
private void DoEmailStuff()
{
// Statment For Sending The Email under conditions
}
private void AnotherEmailStuff()
{
// Another Statment for Sending Email
}
void Application_Start(object sender, EventArgs e)
{
RegistermyCacheEntries();
}
private bool RegistermyCacheEntries()
{
if (null != HttpContext.Current.Cache[CacheItemKey]) return false;
HttpContext.Current.Cache.Add(CacheItemKey, "Test", null,
DateTime.MaxValue, TimeSpan.FromHours(24),
CacheItemPriority.Normal,
new CacheIRemovedCallback(CacheIRemovedCallback));
return true;
}
答案 0 :(得分:1)
试试这个:
HttpContext.Current.Cache.Add(CacheItemKey, "Test", null,
DateTime.Now.AddHours(24), System.Web.Caching.Cache.NoSlidingExpiration,
CacheItemPriority.Normal,
new CacheIRemovedCallback(CacheIRemovedCallback));
public Object Add(
string key,
Object value,
CacheDependency dependencies,
DateTime absoluteExpiration,
TimeSpan slidingExpiration,
CacheItemPriority priority,
CacheItemRemovedCallback onRemoveCallback
)
保证项目在缓存中保留至少10分钟,这是默认设置。因此,每10分钟发送一次电子邮件意味着设置到期时间不成功。您可以使用absoluteExpiration和slidingExpiration参数更改它。 但我怀疑这个问题还存在于其他地方。尝试插入而不是 添加方法,如here
所示