Load objects into cache from new thread

倖福魔咒の 提交于 2020-01-06 12:47:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!