I have this class which fires a method and forget it.. the only problem is, if the method am calling has an HttpContext it throws NullReferenceException.
My gues is that I can’t use Httpcontext inside the ThreadPool.QueueUserWorkItem(dynamicInvokeShim, new TargetInfo(d, args)); because I am getting NullReferenceException is there a work around for it?
Method with Httpcontext:
public static DataTable GetDataTable(string name)
{
return (DataTable)HttpContext.Current.Cache[name];
}
method that fires and forget a method:
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());
}
}
}
}
Like usr said:
HttpContext.Currentis only available on the thread executing a request, and a thread pool thread you started is not that same thread.However, if you want to access the ASP.NET cache, you can also use
HttpRuntime.Cache, which is a static property which is available from each thread. (HttpContext.Current.Cachesimply returnsHttpRuntime.Cacheso you don’t need to worry about any difference.)Note that it is ill advised to pass the HttpContext instance received from
HttpContext.Currentto another thread: by the time the other thread runs, the request corresponding with the captured HttpContext could already have ended, so you could end up with an HttpContext instance that is broken.