使用HttpContext在目标上的ThreadPool QueueUserWorkItem错误

rpm*_*ins 2 .net c# threadpool

我有这个类,它触发一个方法并忘记它..唯一的问题是,如果调用的方法有HttpContext它抛出NullReferenceException.

我的理由是我不能Httpcontext在里面使用,ThreadPool.QueueUserWorkItem(dynamicInvokeShim, new TargetInfo(d, args));因为我得到的NullReferenceException 是它的工作吗?

方法Httpcontext:

public static DataTable GetDataTable(string name)
{
    return (DataTable)HttpContext.Current.Cache[name];
}
Run Code Online (Sandbox Code Playgroud)

触发并忘记方法的方法:

using System;
using System.Threading;

namespace XGen.Kuapo.BLL
{
  public class AsyncHelper
  {
      class TargetInfo
      {
          internal TargetInfo(Delegate d, object[] args)
          {
              Target = d;
              Args = args;
          }

          internal readonly Delegate Target;
          internal readonly object[] Args;
      }

      private static WaitCallback dynamicInvokeShim = new WaitCallback(DynamicInvokeShim);

      public static void FireAndForget(Delegate d, params object[] args)
      {
          ThreadPool.QueueUserWorkItem(dynamicInvokeShim, new TargetInfo(d, args));
      }

      static void DynamicInvokeShim(object o)
      {
          try
          {
              TargetInfo ti = (TargetInfo)o;
              ti.Target.DynamicInvoke(ti.Args);
          }
          catch (Exception ex)
          {
              // Only use Trace as is Thread safe
              System.Diagnostics.Trace.WriteLine(ex.ToString());
          }
      }
  }
}
Run Code Online (Sandbox Code Playgroud)

Rub*_*ben 6

就像usr所说:HttpContext.Current只在执行请求的线程上可用,并且您启动的线程池线程不是同一个线程.

但是,如果要访问ASP.NET缓存,还可以使用HttpRuntime.Cache,这是一个可从每个线程获得的静态属性.(HttpContext.Current.Cache只需返回,HttpRuntime.Cache这样您就不必担心任何差异.)

请注意,建议将接收到的HttpContext实例传递HttpContext.Current给另一个线程:到另一个线程运行时,与捕获的HttpContext对应的请求可能已经结束,因此您可能最终得到一个被破坏的HttpContext实例.