我有这个类会触发一个方法并忘记它。唯一的问题是,如果正在调用的方法有一个HttpContext
它会抛出NullReferenceException
。
我的猜测是我不能Httpcontext
在里面使用,ThreadPool.QueueUserWorkItem(dynamicInvokeShim, new TargetInfo(d, args));
因为我得到NullReferenceException
了解决办法吗?
方法Httpcontext
:
public static DataTable GetDataTable(string name)
{
return (DataTable)HttpContext.Current.Cache[name];
}
触发并忘记方法的方法:
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());
}
}
}
}