从新线程将对象加载到缓存中
我正在尝试使用 BackgroundWorker 类启动一个新线程,在网站启动时将大量对象加载到缓存中。
到目前为止我的代码:
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?
}
我将代码放在 Global.asax.cs 中,并在 Application_Start
事件期间调用 PreLoadCachedSearches
:新线程已启动,但每当它失败时它尝试通过 HttpContext.Current.Cache
访问缓存,该缓存为 null。我假设 HttpContext 在我用 BackgroundWorker 启动的新线程中不存在/不可用。 我还尝试将代码移至单独的页面并手动启动线程,而不是通过 Application_Start 事件 - 同样的问题。
如果我在 Web 应用程序的上下文中调用缓存加载代码(即无线程),它就可以正常工作。
- 我该如何解决这个问题?传入对主线程缓存的引用或以某种方式访问它?
这个问题是上一个问题的延续,ASP.NET 中的异步任务。
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.
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?
}
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.
- How do I work around this? Pass in a reference to the cache of the main thread or access it somehow?
This question is a continuation of this previous question, Asynchronous task in ASP.NET.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您没有 HttpContext,因为该线程不参与服务 Http 请求。
尝试 HttpRuntime.Cache
You don't have an HttpContext because the thread isn't involved in servicing an Http Request.
Try
HttpRuntime.Cache
您可以通过传递 HttpContex.Current 作为参数来实现;
You can do it by passing HttpContex.Current as parameter;