I am using .AsParallel().ForAll() to enumerate a collection in parallel in the context of an ASP.NET request. The enumeration method relies on System.Threading.Thread.CurrentPrincipal.
Can I rely on the individual threads used to have their System.Threading.Thread.CurrentPrincipal set to the HttpContext.Current.User of the thread that is processing the ASP.NET Request or do I need to manage that myself?
Another way of asking the question is do the threads used by PLINQ inherit the identity of the thread that invoked the operation?
No, the identity will not be propagated to these worker threads automatically. If, in fact, the components you are using are
HttpContext.Userwhat you can do is capture the current, “ambient”HttpContextinstance in your “main” thread and propagate it to your worker threads. That would look something like this:This works because
HttpContext.Currentis backed by a thread static, so every worker thread will be assigned the instance from your main thread and any work done on it from that point will see that as the current instance.Now, you have to be aware that
HttpContextand its related classes were not designed to be thread safe, so this is a bit of a hack. If you’re only reading from properties this isn’t really a problem. If you are not using components that rely onHttpContext.Currentthen it would be “cleaner” to not set that and instead just use the capturedcurrentHttpContextvariable directly in the worker.Finally, if all you really need is to propagate the current principal to the worker threads then you can do just that instead using the same approach: