从新线程将对象加载到缓存中

时间:2011-04-22 10:42:43

标签: c# asp.net multithreading caching .net-3.5

我正在尝试使用BackgroundWorker class启动一个新线程,该线程在网站启动时将大量对象加载到缓存中。

到目前为止我的代码:

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中并在PreLoadCachedSearches事件期间调用Application_Start:新线程已启动,但每当尝试通过{访问缓存时失败{1}}为空。我假设HttpContext不存在/在我使用BackgroundWorker开始的新线程中不可用。 我也尝试将代码移动到一个单独的页面并手动启动线程而不是通过Application_Start事件 - 同样的问题。
如果我在Web应用程序的上下文中调用缓存加载代码(即没有线程),它就可以正常工作。

  • 我该如何解决这个问题?传入对主线程缓存的引用或以某种方式访问​​它?

这个问题是上一个问题的延续,Asynchronous task in ASP.NET

2 个答案:

答案 0 :(得分:3)

您没有HttpContext,因为该线程不涉及为Http请求提供服务。

尝试HttpRuntime.Cache

答案 1 :(得分:1)

您可以通过将HttpContext.Current作为参数传递来执行此操作;

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?
}