Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8731303
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T09:12:21+00:00 2026-06-13T09:12:21+00:00

Say, I have the following code: IPrincipal capturedPrincipal = Thread.CurrentPrincipal; myseq.AsParallel().Select(x => { Thread.CurrenctPrincipal

  • 0

Say, I have the following code:

IPrincipal capturedPrincipal = Thread.CurrentPrincipal;
myseq.AsParallel().Select(x =>
{
    Thread.CurrenctPrincipal = capturedPrincipal;
    /*call code protected with CAS*/
});

to be sure Thread.CurrenctPrincipal will be propagated to every thread where Select‘s delegate will be executed on. I’ve realized that if I had proper SynchronizationContext set up this would happen automatically. So does PLINQ use SynchronizationContext when queuing work items on ThreadPool? And if no, why?

p.s.

I think it’s important to note that the code above is executed in WCF environment hosted under IIS/WAS (no ASP.NET compatibility).

Edit:
Found a similar question confirming same behavior I witness.

Edit2:
Modified casperOne’s test a bit and it fails saying threadid is the same:

    [Test]
    public void Test1()
    {
        var principal = new GenericPrincipal(new GenericIdentity("test"), new string[0]);
        Thread.CurrentPrincipal = principal;
        int threadID = Thread.CurrentThread.ManagedThreadId;

        Enumerable.Range(0, 4000).AsParallel()
            .WithExecutionMode(ParallelExecutionMode.ForceParallelism)
            .Select(x =>
                {
                    Assert.AreSame(Thread.CurrentPrincipal, principal);
                    Assert.AreNotEqual(Thread.CurrentThread.ManagedThreadId, threadID);
                    return x;
                })
            .ToArray();
    }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T09:12:22+00:00Added an answer on June 13, 2026 at 9:12 am

    There are two questions here. The first is whether or not Thread.CurrentPrincipal is propagated to threads in PLINQ.

    The answer is yes, as this is part of the ExecutionContext and the ExecutionContext is captured from the calling thread and copied to the new/recycled thread when a new thread/task/thread pool thread is started.

    The following test case (run in .NET 4.0) shows this:

    [TestMethod]
    public void TestMethod1()
    {
        // Capture the current logged in account.
        // Could be a GenericPrincipal as well with some random value
        // set on the identity name.
        IPrincipal p = new WindowsPrincipal(WindowsIdentity.GetCurrent());
    
        // Set the current principal.
        Thread.CurrentPrincipal = p;
    
        // Set the synchronization context.
        SynchronizationContext.SetSynchronizationContext(
            new SynchronizationContext());
    
        // Context is not null.
        Assert.IsNotNull(SynchronizationContext.Current);
    
        // PLINQ.
        var plinqThreadDetails = 
            // Go parallel.  This number needs to be reasonably
            // high to force parallelization as PLINQ might
            // use this thread if the size is small.
            from i in Enumerable.Range(0, 4000).AsParallel().
                // Force parallelization.  At best, this is
                // a suggestion.
                WithExecutionMode(ParallelExecutionMode.ForceParallelism)
            select new {
                // These values are retreived on another thread.
                IdentityName = Thread.CurrentPrincipal.Identity.Name,
                Thread.CurrentThread.ManagedThreadId,
            };
    
        // Was there any parallelization?
        bool anyParallel = false;
    
        // Make assertions.
        // The managed thread id is different than the current one.
        foreach (var plinqThreadDetail in plinqThreadDetails)
        { 
            // But the principal still flowed, even though on a different
            // thread.
            Assert.AreEqual(Thread.CurrentPrincipal.Identity.Name,
                plinqThreadDetail.IdentityName);
    
            // Update any parallel.
            anyParallel |= (plinqThreadDetail.ManagedThreadId !=
                Thread.CurrentThread.ManagedThreadId);
        }
    
        // There was *some* parallelization.
        Assert.IsTrue(anyParallel);
    }
    

    Regarding whether or not SynchronizationContext is used in PLINQ, it’s not, and it doesn’t make sense to.

    Considering that using a SynchronizationContext usually means serializing a call to a particular context (which is usually a thread, think UI applications, but not always, given the ASP.NET synchronization context), you’d kill any gains that PLINQ would gain from parallelization because every call would have to be marshaled back through the SynchronizationContext.

    The benefits in PLINQ come from being able to execute these operations at the same time, not one-at-a-time.

    The following test case (very much along the lines of the previous one) proves that the SynchronizationContext is not captured for PLINQ threads:

    [TestMethod]
    public void TestMethod2()
    {
        // Set the synchronization context.
        SynchronizationContext.SetSynchronizationContext(
            new SynchronizationContext());
    
        // Context is not null.
        Assert.IsNotNull(SynchronizationContext.Current);
    
        // PLINQ.
        var plinqThreadDetails = 
            // Go parallel.  This number needs to be reasonably
            // high to force parallelization as PLINQ might
            // use this thread if the size is small.
            from i in Enumerable.Range(0, 4000).AsParallel().
                // Force parallelization.
                WithExecutionMode(ParallelExecutionMode.ForceParallelism)
            select new {
                // These values are retreived on another thread.
                SynchronizationContextIsNull =
                    SynchronizationContext.Current == null,
                Thread.CurrentThread.ManagedThreadId,
            };
    
        // Make assertions.
        // Was there any parallelization?
        bool anyParallel = false;
    
        // Make assertions.
        // The synchronization context on the PLINQ thread was
        // not set, only if on a different thread.
        foreach (var plinqThreadDetail in plinqThreadDetails)
        {
            // If the thread id is different.
            if (plinqThreadDetail.ManagedThreadId !=
                Thread.CurrentThread.ManagedThreadId)
            {
                // The synchronization context was null.
                Assert.IsTrue(plinqThreadDetail.SynchronizationContextIsNull);
    
                // There was something on another thread.
                anyParallel = true;
            }
            else
            {
                // The synchronization context is not null.
                Assert.IsFalse(plinqThreadDetail.SynchronizationContextIsNull);
            }
        }
    
        // There was *some* parallelization.
        Assert.IsTrue(anyParallel);
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Let's say we have following code: struct A{ virtual ~A(){} void f(){ p =
Say I have the following code: <span>Hello world!</span> And the following CSS: span{ color:red;
Say I have the following code: <div onclick='location.href=http://www.example.com/'> <a href='#' onclick='alert(blah)'>click</a> </div> Is there
Say I have the following code: class Parent { static string MyField = ParentField;
Say I have the following code: struct date { int day; int month; int
Lets say I have the following code: import collections d = collections.OrderedDict() d['foo'] =
Let's say I have the following code: class MyClass(object): def __init__(self, param): self.param =
Let's say I have the following code, file1 = open(myfile,w) #Write to file1... #Open
Let's say I have the following Code: <div id=parent> <div id=child></div> </div> Now I
Let's say we have the following code in a class: //class code TextBox t

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.