装入对象到新线程缓存 [英] Load objects into cache from new thread
问题描述
我试图使用 BackgroundWorker的类开始一个新的线程,加载大量的对象到缓存中,当启动该网站。
I'm trying to use the BackgroundWorker class to start a new thread which loads a large number of objects into the cache when the website is started.
我的code到目前为止:
My code so far:
private void PreLoadCachedSearches()
{
var worker = new BackgroundWorker() { WorkerReportsProgress = false, WorkerSupportsCancellation = true };
worker.DoWork += new DoWorkEventHandler(DoWork);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(WorkerCompleted);
worker.RunWorkerAsync();
}
private static void DoWork(object sender, DoWorkEventArgs e)
{
// Do the cache loading...
var x = HttpContext.Current.Cache; // BUT the Cache is now null!!!!
}
private static void WorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// Logging?
}
我把code中的Global.asax.cs并调用 preLoadCachedSearches
在的Application_Start
事件:新线程启动,但它失败时,它试图访问通过 HttpContext.Current.Cache
这是空。我假设的HttpContext不存在/不在新的线程,我与BackgroundWorker的开球可用。
我也试着动了code到一个单独的页面,并启动线程手动,而不是通过Application_Start事件 - 同样的问题
如果我把我的缓存加载code在Web应用程序的情况下(即没有线程)它工作得很好。
I put the code in Global.asax.cs and call PreLoadCachedSearches
during the Application_Start
event: The new thread is started, but it fails whenever it tries to access the cache via HttpContext.Current.Cache
which is null. I assume HttpContext doesn't exist/isn't available in the new thread I'm kicking off with the BackgroundWorker.
I've also tried moving the code to a separate page and start the thread manually rather than via the Application_Start event - same problem.
If I call my cache-loading code in the context of the web application (i.e. no threading) it works just fine.
- 如何解决此问题?传递一个引用到主线程的缓存或以某种方式访问它?
此问题是延续了这一previous问题,在ASP.NET 异步任务。
This question is a continuation of this previous question, Asynchronous task in ASP.NET.
推荐答案
您没有一个HttpContext的,因为线程不参与服务的HTTP请求。
You don't have an HttpContext because the thread isn't involved in servicing an Http Request.
尝试 HttpRuntime.Cache
这篇关于装入对象到新线程缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!