Parallel.For in web services uses different identity than the web service?
-
Monday, February 14, 2011 9:35 PM
We've been experimenting with some web services that mine data from multiple locations. In these experiments, we were looking at Parallel.For and Parallel.ForEach to potentially do the data mining in parallel then return the aggregated responses.
However, we were getting failures because the identity we run the web service under (which has database permissions) is not the same as the identity for the threads in the ThreadPool.
So, my questions are:
1) Is there a way to set the identity used in Parallel.For and ForEach?
2) Do tasks have this issue too?
Thanks in advance!
James Michael Hare
Blog: http://www.geekswithblogs.net/BlackRabbitCoder
Twitter: @BlkRabbitCoder
There are 10 kinds of people in the world: those who know binary and those who don't...
All Replies
-
Monday, February 14, 2011 10:06 PMModerator
By default, Parallel.For and ForEach will use the ThreadPool for their scheduling since they use the default TaskScheduler.
However, you can easily schedule a Task using a custom task scheduler, which could be setup to include your identity handling. For example, this MSDN sample shows how to create a custom Task scheduler and use it to schedule tasks via creating a custom TaskFactory.
You could use this same technique to create a factory that would start your tasks on your own, self-managed threads, where each thread had it's identity setup prior to execution. This would allow you to use Tasks in this situation.
In addition, you could use the overloads of Parallel.For which take a ParallelOptions class. This lets you specify a TaskScheduler to use for scheduling the work items. If you used your custom one above, Parallel.For would work.
Reed Copsey, Jr. - http://reedcopsey.com
If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".- Marked As Answer by James Michael HareMVP Tuesday, February 15, 2011 4:53 AM
-
Tuesday, February 15, 2011 4:53 AMReed, thanks as always for a great response!
James Michael Hare
Blog: http://www.geekswithblogs.net/BlackRabbitCoder
Twitter: @BlkRabbitCoder
There are 10 kinds of people in the world: those who know binary and those who don't...
-
Friday, April 20, 2012 6:29 PM
In case anyone wants a simpler, though less structured solution, you can try something like this:
using System.Threading;
using System.Threading.Tasks;
using System.Security.Principal;// save the identity so new threads later can impersonate the user identity
WindowsIdentity identity = WindowsIdentity.GetCurrent();
Parallel.For(0, n, i =>
{
// the new thread uses the system identity by default - we want it to use the identity of the
// main thread instead
using (WindowsImpersonationContext impersonationContext = identity.Impersonate())
{
Do main thread work…
}
};

