不,身份不会自动传播到这些工作线程。实际上,如果您正在使用的组件是HttpContext.User
您可以做的,那么您可以HttpContext
在“主”线程中捕获当前的“环境”实例并将其传播到您的工作线程。看起来像这样:
HttpContext currentHttpContext = HttpContext.Current;
myWorkItems.AsParallel().ForAll(wi =>
{
HttpContext.Current = currentHttpContext;
try
{
// anything called from here out will find/use the context of your original ASP.NET thread
}
finally
{
// Disassociate the context from the worker thread so that it is not held on to beyond its official lifetime
HttpContext.Current = null;
}
});
这是有效的,因为HttpContext.Current
它由线程静态支持,因此每个工作线程都将从您的主线程分配一个实例,并且从那时起对其进行的任何工作都会将其视为当前实例。
现在,您必须意识到,HttpContext
它及其相关的类并非设计为线程安全的,所以这有点像 hack。如果您只是从属性中读取,这不是一个真正的问题。如果您不使用依赖的组件,HttpContext.Current
那么不设置它会更“干净”,而是currentHttpContext
直接在工作程序中使用捕获的变量。
最后,如果您真正需要的只是将当前主体传播到工作线程,那么您可以使用相同的方法来做到这一点:
Principal logicalPrincipal = Thread.CurrentPrincipal;
myWorkItems.AsParallel().ForAll(wi =>
{
Principal originalWorkerThreadPrincipal = Thread.CurrentPrincipal;
Thread.CurrentPrincipal = logicalPrincipal;
try
{
// anything called from here out will find the principal from your original thread
}
finally
{
// Revert to the original identity when work is complete
Thread.CurrentPrincipal = originalWorkerThreadPrincipal;
}
});