c# - 如何在 DataFlow Block 中为每个线程创建对象,但不是每个请求的对象?
问题描述
我有一个代码示例
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
每个线程定义一个对象并在处理请求时重用同一个对象?
解决方案
感谢Reed Copsey 的精彩文章和 Theodor Zoulias 的提醒ThreadLocal<T>
。
新的 ThreadLocal 类为我们提供了一个强类型、本地范围的对象,我们可以使用它来设置为每个线程单独保存的数据。这允许我们使用每个线程存储的数据,而不必将静态变量引入我们的类型。在内部,ThreadLocal 实例将自动设置静态数据,管理其生命周期,执行与我们特定类型之间的所有转换。这使得开发变得更加简单。
// 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);
推荐阅读
- etcd - etcd v3 中“Watch key changes”的最佳实践
- javascript - Javascipt嵌套而循环未结束
- azure - Azure B2C:删除令牌过期
- istio - 在 istio-proxy 和 egress gateway 之间使用自定义 mTLS 发起 egress 流量的 mTLS
- flutter - 如何在flutter中动态生成网格视图?
- traefik - 使用 `swarmMode = true` 运行 traefik 的优缺点是什么?
- c++ - 在 qt5 之前发送数据
- javascript - 使用 html() 方法时如何解决 jsPdf 中的 UTF-8 问题?
- android - 无法通过地理定位器在 Flutter 中检索位置
- python - 升级/更新 Anaconda