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 8507901
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T03:00:02+00:00 2026-06-11T03:00:02+00:00

(Posting this with answer because I couldn’t find a full explanation of how to

  • 0

(Posting this with answer because I couldn’t find a full explanation of how to do this anywhere, so I thought it might have some value for someone)

How can I set the processor affinity of a particular thread in Microsoft .Net? Setting the process’s affinity is trivial via System.Diagnostics.Process.ProcessorAffinity, but the System.Threading.Thread class offers no such functionality and .Net doesn’t guarantee a managed thread is linked to any particular operating system thread.

  • 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-11T03:00:04+00:00Added an answer on June 11, 2026 at 3:00 am

    The separation between managed and operating system threads dates back to .Net 2.0, and plans by the SQL Server team to implement .Net threads using fibers. This never really went anywhere, so while there is no guarantee that a managed thread will always run on the same operating system thread, in practice this is always the case for all current .Net hosts. Given that this hasn’t changed in all the years since .Net 2.0’s introduction, it is unlikely this will ever change.

    It is possible to strengthen our confidence even for future versions of .Net by using the System.Threading.Thread.BeginThreadAffinity method. This guarantees that the managed thread will stay on the same operating system thread (so it does nothing on the default CLR host, as that is already true by default). I suppose it is still possible that other managed threads can share the same operating system thread, but this seems unlikely and is definitely not the case in any current .Net hosts.

    .Net provides the ability to access native operating system threads using the System.Diagnostics.ProcessThread class, and this class has the ability to change the thread’s processor affinity using the ProcessorAffinity property. However, linking a particular managed thread to its ProcessThread was made deliberately difficult.

    The only real way to do it is from inside the thread itself. Use the System.AppDomain.GetCurrentThreadId method (or PInvoke the GetCurrentThreadId function if you don’t want to call a deprecated method, though that would not work with Mono on operating systems other than Windows). This can then be matched to the ProcessThread.Id property.

    This makes it possible to set the thread’s processor affinity with the following code (to be called from inside the thread):

    /// <summary>
    /// Sets the processor affinity of the current thread.
    /// </summary>
    /// <param name="cpus">A list of CPU numbers. The values should be
    /// between 0 and <see cref="Environment.ProcessorCount"/>.</param>
    public static void SetThreadProcessorAffinity(params int[] cpus)
    {
        if( cpus == null )
            throw new ArgumentNullException("cpus");
        if( cpus.Length == 0 )
            throw new ArgumentException("You must specify at least one CPU.", "cpus");
    
        // Supports up to 64 processors
        long cpuMask = 0;
        foreach( int cpu in cpus )
        {
            if( cpu < 0 || cpu >= Environment.ProcessorCount )
                throw new ArgumentException("Invalid CPU number.");
    
            cpuMask |= 1L << cpu;
        }
    
        // Ensure managed thread is linked to OS thread; does nothing on default host in current .Net versions
        Thread.BeginThreadAffinity();
    
    #pragma warning disable 618
        // The call to BeginThreadAffinity guarantees stable results for GetCurrentThreadId,
        // so we ignore the obsolete warning
        int osThreadId = AppDomain.GetCurrentThreadId();
    #pragma warning restore 618
    
        // Find the ProcessThread for this thread.
        ProcessThread thread = Process.GetCurrentProcess().Threads.Cast<ProcessThread>()
                                   .Where(t => t.Id == osThreadId).Single();
        // Set the thread's processor affinity
        thread.ProcessorAffinity = new IntPtr(cpuMask);
    }
    

    Keep in mind that while this works on current versions of .Net, theoretically the lack of a guarantee that managed threads are bound to OS threads could break this code in the future. However, I consider this extremely unlikely.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I admit...I am posting this question because I still don't have an answer to
I feel very very very silly posting this, but I can't find the answer.
I am posting this question because I had a complete answer for this written
I know the answer to this, but I'm posting this here because as an
Note: I am cross-posting this from App Engine group because I got no answers
I am trying to integrated linkedIn using this question answer Posting LinkedIn message from
Posting this one for a friend. They have an Icefaces app that uses Icefaces's
I have seen many posting this issue in SO. I have gone through those
Ok, I hope I've got everything listed up nicely before posting this question because
I've searched a lot but I couldn't find the proper answer to my question

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.