我有一个代码样本
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对象,并在处理请求时重用同一个对象?
发布于 2021-05-08 17:23:49
感谢里德·科普西为了这篇好文章和西奥多·祖利亚斯提醒我有关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);https://stackoverflow.com/questions/67272403
复制相似问题