【问题标题】:Load objects into cache from new thread从新线程将对象加载到缓存中
【发布时间】:2011-04-22 10:42:43
【问题描述】:

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

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

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

【问题讨论】:

  • backgroundworker 适用于 WinForms 和 WPF。它在 ASP.NET 应用程序中没有用。
  • 我就是这么想的!但是有几个人评论说它可以在 ASP.NET 中使用...

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


【解决方案1】:

您没有 HttpContext,因为线程不参与服务 Http 请求。

试试HttpRuntime.Cache

【讨论】:

  • 这也是在WinForm应用程序中使用HttpRuntime缓存的方式。
【解决方案2】:

您可以通过传递 HttpContex.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?
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    • 2019-05-24
    • 1970-01-01
    • 1970-01-01
    • 2011-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多