How to get thread Id in C#

15,529

Thread.CurrentThread.ManagedThreadId gets the managed thread ID of the currently executing thread.

If you want to get the native thread ID instead (not something you normally want to do) you can call the method AppDomain.GetCurrentThreadId() (obsoleted "because it does not provide a stable Id when managed threads are running on fibers" but as far as I know managed threads are only running on fibers inside SQL Server).

Share:
15,529
Recawo
Author by

Recawo

Updated on June 04, 2022

Comments

  • Recawo
    Recawo almost 2 years
    public bool HasItemsFromPropertySet(InfoItemPropertySet propertySet, CompositeInfoItem itemRemoved)
        {
            var itemAndSubItems = new InfoItemCollection();
            if (itemRemoved != null)
            {
                itemAndSubItems.Add(itemRemoved);
                //foreach (InfoItem item in itemRemoved.AllDescendants)
                itemAndSubItems.AddRange(itemRemoved.AllDescendants);
            }
            return AllItems.AsParallel().Any(item => item.PropertySet == propertySet && !itemAndSubItems.Contains(item));
        }
    


    Above in my code I use AsParallel().Any() How can i get thread ID of thread generated by that AsParellel.Any()...

  • Recawo
    Recawo about 12 years
    To find thread Id of currently executing thread in above case I have to write Thread.CurrentThread.ManagedThreadId inside AsParallel().Any( item => {//here I guess//}); but That line does not work because that line only contains predicate.
  • Martin Liversage
    Martin Liversage about 12 years
    @Recawo: But what is it that you want to do? Anyway, you can easily create a predicate that queries the current thread ID either by wrapping it into a function or writing it inline like this item => { ... C# statements ... ; return result; }.