如何在数据流块中为每个线程创建对象而不是为每个请求创建对象?

问题描述 投票:0回答:1

我有代码示例

var options = new ExecutionDataflowBlockOptions();
var actionBlock = new ActionBlock<int>(async request=>{
         var rand = new Ranodm();
         //do some stuff with request by using rand
},options);

这段代码的问题是,在每个请求中我都必须创建新的

rand
对象。有一种方法可以为每个线程定义一个
rand
对象并在处理请求时重复使用同一对象?

c# task-parallel-library dataflow tpl-dataflow
1个回答
1
投票

感谢 Reed Copsey 的好文章 和 Theodor Zoulias 的提醒

ThreadLocal<T>

新的 ThreadLocal 类为我们提供了强类型、 我们可以使用本地范围的对象来设置保持独立的数据 对于每个线程。这允许我们使用每个线程存储的数据, 无需在我们的类型中引入静态变量。 在内部,ThreadLocal 实例会自动设置 静态数据,管理其生命周期,进行所有的转换 我们的具体类型。这使得开发变得更加简单。

msdn 示例:

 // Demonstrates:
    //      ThreadLocal(T) constructor
    //      ThreadLocal(T).Value
    //      One usage of ThreadLocal(T)
    static void Main()
    {
        // Thread-Local variable that yields a name for a thread
        ThreadLocal<string> ThreadName = new ThreadLocal<string>(() =>
        {
            return "Thread" + Thread.CurrentThread.ManagedThreadId;
        });

        // Action that prints out ThreadName for the current thread
        Action action = () =>
        {
            // If ThreadName.IsValueCreated is true, it means that we are not the
            // first action to run on this thread.
            bool repeat = ThreadName.IsValueCreated;

            Console.WriteLine("ThreadName = {0} {1}", ThreadName.Value, repeat ? "(repeat)" : "");
        };

        // Launch eight of them.  On 4 cores or less, you should see some repeat ThreadNames
        Parallel.Invoke(action, action, action, action, action, action, action, action);

        // Dispose when you are done
        ThreadName.Dispose();
    }

所以你的代码会像这样:

ThreadLocal<Random> ThreadName = new ThreadLocal<Random>(() =>
{
    return new Random();
});


var options = new ExecutionDataflowBlockOptions
{
    MaxDegreeOfParallelism = 4,
    EnsureOrdered = false,
    BoundedCapacity = 4 * 8
};
var actionBlock = new ActionBlock<int>(async request =>
{
    bool repeat = ThreadName.IsValueCreated;
    var random = ThreadName.Value; // your local random class
    Console.WriteLine($"Thread: {Thread.CurrentThread.ManagedThreadId},  
        repeat: ", repeat ? "(repeat)" : "");

 }, options);
© www.soinside.com 2019 - 2024. All rights reserved.