我正在使用 ASP.Net Web API 2 / .Net 4.5.2。
在排队后台工作项时,我试图保留调用主体。为此,我试图:
Thread.CurrentPrincipal = callingPrincipal;
但是当我这样做时,我得到一个 ObjectDisposedException:
System.ObjectDisposedException:安全句柄已关闭
如何将当前主体保留在后台工作项中?
我可以以某种方式复制校长吗?
public void Run<T>(Action<T> action)
{
_logger.Debug("Queueing background work item");
var callingPrincipal = Thread.CurrentPrincipal;
HostingEnvironment.QueueBackgroundWorkItem(token =>
{
try
{
// UNCOMMENT - THROWS EXCEPTION
// Thread.CurrentPrincipal = callingPrincipal;
_logger.Debug("Executing queued background work item");
using (var scope = DependencyResolver.BeginLifetimeScope())
{
var service = scope.Resolve<T>();
action(service);
}
}
catch (Exception ex)
{
_logger.Fatal(ex);
}
finally
{
_logger.Debug("Completed queued background work item");
}
});
}