How to manage Thread Local Storage (TLS) when using TPL?

前端 未结 3 756
别那么骄傲
别那么骄傲 2021-02-14 10:48

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 als

3条回答
  •  灰色年华
    2021-02-14 11:17

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

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

提交回复
热议问题