问题
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.
回答1:
You don't have an HttpContext because the thread isn't involved in servicing an Http Request.
Try HttpRuntime.Cache
回答2:
You can do it by passing HttpContex.Current as parameter;
private void PreLoadCachedSearches()
{
var worker = new BackgroundWorker() { WorkerReportsProgress = false, WorkerSupportsCancellation = true };
worker.DoWork += new DoWorkEventHandler(DoWork);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(WorkerCompleted);
worker.RunWorkerAsync(HttpContext.Current);
}
private static void DoWork(object sender, DoWorkEventArgs e)
{
HttpContext.Current = (HttpContext)e.Argument;
var x = HttpContext.Current.Cache;
}
private static void WorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// Logging?
}
来源:https://stackoverflow.com/questions/5754612/load-objects-into-cache-from-new-thread