如何线程本地存储(TLS)使用TPL时管理? [英] How to manage Thread Local Storage (TLS) when using TPL?

查看:144
本文介绍了如何线程本地存储(TLS)使用TPL时管理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要存储日志的上下文信息,TLS,这样我可以设置在入口点的值,并在所有导致堆栈提供该值。这项工作做得很好,但我也使用第三方物流和线程池。这个问题就变成如何将TLS数据迁移到其他线程。我可以做这一切我自己,但我失去了很好的方法,比如的Parallel.For。

I want to store logging context information in TLS so that I can set a value at the entry point, and have that value available in all resulting stacks. This work well, but I also using TPL and the ThreadPool. The problem then becomes how to migrate TLS data to the other threads. I can do it all myself, but then I lose nice methods like Parallel.For.

有没有一些方法,以在使用第三方物流时,TLS复制?这也适用于C#时,得到的计谋功能。

Is there some way to have TLS copied when using TPL? This will also apply to C# when it gets the await feature.

谢谢, 埃里克

推荐答案

通常情况下,这是通过使用的的Parallel.For 已经提供了线程本地数据。

Typically, this is handled via using an overload of Parallel.For that already provides for thread local data.

此重载允许您提供一个初始化和定稿委托,从而有效地成为每个线程初始化为你的线程本地数据,并减少功能,在年底合并的结果结合起来(这是每个线程运行一次)。 <一href="http://reedcopsey.com/2010/01/22/parallelism-in-net-part-4-imperative-data-parallelism-aggregation/"相对=nofollow>我详细写了一篇关于这个这里。

This overload allows you to provide an initialization and a finalization delegate, which effectively becomes an initialization per thread for your thread local data, and a reduction function at the end to "merge" the results together (which is run once per thread). I wrote about this in detail here.

的基本形式是做这样的事情:

The basic form is to do something like:

object sync = new object();
double result = 0;

Parallel.For(0, collection.Count, 
    // Initialize thread local data:
    () => new MyThreadSpecificData(),
    // Process each item
    (i, pls, currentThreadLocalData) => 
    {
        // Generate a NEW version of your local state data
        MyThreadSpecificData newResults = ProcessItem(collection, i, currentThreadLocalData);
        return newResults;
    },
    // Aggregate results
    threadLocalData =>
    {
       // This requires synchronization, as it happens once per thread, 
       // but potentially simultaneously
       lock(sync)
          result += threadLocalData.Results;
    });

这篇关于如何线程本地存储(TLS)使用TPL时管理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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