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

  • SEARCH
  • Home
  • 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 3501374
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T12:51:04+00:00 2026-05-18T12:51:04+00:00

Before using the Task Parallel Library, I have often used CorrelationManager.ActivityId to keep track

  • 0

Before using the Task Parallel Library, I have often used CorrelationManager.ActivityId to keep track of tracing/error reporting with multiple threads.

ActivityId is stored in Thread Local Storage, so each thread get’s its own copy. The idea is that when you fire up a thread (activity), you assign a new ActivityId. The ActivityId will be written to the logs with any other trace information, making it possible to single out the trace information for a single ‘Activity’. This is really useful with WCF as the ActivityId can be carried over to the service component.

Here is an example of what I’m talking about:

static void Main(string[] args)
{
    ThreadPool.QueueUserWorkItem(new WaitCallback((o) =>
    {
        DoWork();
    }));
}

static void DoWork()
{
    try
    {
        Trace.CorrelationManager.ActivityId = Guid.NewGuid();
        //The functions below contain tracing which logs the ActivityID.
        CallFunction1();
        CallFunction2();
        CallFunction3();
    }
    catch (Exception ex)
    {
        Trace.Write(Trace.CorrelationManager.ActivityId + " " + ex.ToString());
    }
}

Now, with the TPL, my understanding is that multiple Tasks share Threads. Does this mean that ActivityId is prone to being reinitialized mid-task (by another task)? Is there a new mechanism to deal with activity tracing?

  • 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-05-18T12:51:05+00:00Added an answer on May 18, 2026 at 12:51 pm

    I ran some experiments and it turns out the assumption in my question is incorrect – multiple tasks created with the TPL do not run on the same thread at the same time.

    ThreadLocalStorage is safe to use with TPL in .NET 4.0, since a thread can only be used by one task at a time.

    The assumption that tasks can share threads concurrently was based on an interview I heard about c# 5.0 on DotNetRocks (sorry, I can’t remember which show it was) – so my question may (or may not) become relevant soon.

    My experiment starts a number of tasks, and records how many tasks ran, how long they took, and how many threads were consumed. The code is below if anyone would like to repeat it.

    class Program
    {
        static void Main(string[] args)
        {
            int totalThreads = 100;
            TaskCreationOptions taskCreationOpt = TaskCreationOptions.None;
            Task task = null;
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            Task[] allTasks = new Task[totalThreads];
            for (int i = 0; i < totalThreads; i++)
            {
                task = Task.Factory.StartNew(() =>
               {
                   DoLongRunningWork();
               }, taskCreationOpt);
    
                allTasks[i] = task;
            }
    
            Task.WaitAll(allTasks);
            stopwatch.Stop();
    
            Console.WriteLine(String.Format("Completed {0} tasks in {1} milliseconds", totalThreads, stopwatch.ElapsedMilliseconds));
            Console.WriteLine(String.Format("Used {0} threads", threadIds.Count));
            Console.ReadKey();
        }
    
    
        private static List<int> threadIds = new List<int>();
        private static object locker = new object();
        private static void DoLongRunningWork()
        {
            lock (locker)
            {
                //Keep a record of the managed thread used.
                if (!threadIds.Contains(Thread.CurrentThread.ManagedThreadId))
                    threadIds.Add(Thread.CurrentThread.ManagedThreadId);
            }
            Guid g1 = Guid.NewGuid();
            Trace.CorrelationManager.ActivityId = g1;
            Thread.Sleep(3000);
            Guid g2 = Trace.CorrelationManager.ActivityId;
            Debug.Assert(g1.Equals(g2));
        }
    }
    

    The output (of course this will depend on the machine) was:

    Completed 100 tasks in 23097 milliseconds
    Used 23 threads
    

    Changing taskCreationOpt to TaskCreationOptions.LongRunning gave different results:

    Completed 100 tasks in 3458 milliseconds 
    Used 100 threads
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Has anyone run into this error message before when using a timer on an
I'm using Fedex's web services and getting an annoying error right up front before
I've used Trac/Subversion before and really like the integration. My current project is using
Unfortunately, I need to do this. I'm using ELMAH for my error log. Before
I'd like to execute a task in parallel where each thread needs to have
I'm using GAE and task queue. In queue.yaml file, I keep default setting: 5/s.
I'm working on better understanding Linq-to-SQL before using on a real project, so I'm
I need to run some precompile steps before I build my project using FlexBuilder.
I am currently developing a Rails application using a database that was designed before
Even if you are using Agile, you would need a high level architecture before

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.