如何做任务并行库的任务影响ActivityID? [英] How do Tasks in the Task Parallel Library affect ActivityID?

查看:271
本文介绍了如何做任务并行库的任务影响ActivityID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用任务并行库之前,我经常用CorrelationManager.ActivityId跟踪跟踪/错误多线程汇报。

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

ActivityId存储在线程本地存储,所以每个线程获取的自己的副本。我们的想法是,当你启动一个线程(活动),在设定新的ActivityId。该ActivityId将被写入日志与任何其他跟踪信息,从而能够挑选出一个单一的活动跟踪信息。这与WCF是真正有用的ActivityId可以结转到服务组件。

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());
    }
}

现在,随着TPL,我的理解是,多任务共享线程。这是否意味着ActivityId是容易被重新初始化,中期任务(由其他任务)?是否有一个新的机制来处理活动的跟踪?

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?

推荐答案

我跑了一些实验,事实证明我的问题的假设是不正确 - 与TPL创建了多个任务不会在同一个线程在同一时间运行

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是安全的.NET 4.0 TPL使​​用,因为线程只能在同一时间内使用的一个任务。

这任务可同时共享线程的假设是基于一个我听说过采访的 C#5.0 上的 DotNetRocks (抱歉,我不记得这表明它是) - 。所以我的问题可能会(也可能不会)成为相关很快

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.

我的实验启动多项任务,并记录了多少任务跑,他们耗时多久,有多少线程被消耗。在code低于如果有人想重复一遍。

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

更改taskCreationOpt到TaskCreationOptions.LongRunning给出了不同的结果:

Changing taskCreationOpt to TaskCreationOptions.LongRunning gave different results:

Completed 100 tasks in 3458 milliseconds 
Used 100 threads

这篇关于如何做任务并行库的任务影响ActivityID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆