gpt4 book ai didi

c# - ConcurrentQueue> 的用法

转载 作者:可可西里 更新时间:2023-11-01 08:46:47 26 4
gpt4 key购买 nike

我基本上是在寻找一个线程中从相机获取的图像集合的容器。由于 ConcurrentQueue 是线程安全的,所以我想使用它。但是在调试我的代码时,我发现了 this article

If the elements are small, you’ll probably never notice this. If, however, the elements hold on to large resources (e.g. each element is a huge image bitmap), it’s possible you could see the impact of this (one workaround is to queue a wrapper object, e.g. have a ConcurrentQueue<StrongBox<T>> rather than a ConcurrentQueue<T>, and null out the wrapper’s reference to the T value after the wrapper has been dequeued).

据我所知,StrongBox是一种原始值的包装器。这是否意味着我必须存储另一个图像集合?

所以我正在寻找 ConcurrentQueue<StrongBox<T>>. 的用法或示例我从谷歌上找到的唯一东西是 this code.

最佳答案

过早优化的危险提醒在评论中,所以我将解决这里发生的事情的语义。

正如文章所指出的,ConcurrentQueue可以坚持一些已经经历过的事情的引用。我把它学成“几十”,文章说它不超过 31,这似乎很好地融合了。如果队列跟踪大对象,如 2000x2000 位图,理论上会成为问题。当然,这取决于程序的其余部分在做什么。

将其包装在 StrongBox<T> 中有帮助,因为唯一的事情 StrongBox所做的是坚持对其他事物的引用。因此,StrongBox占地面积非常小,无论它持有什么都会超出范围并且(理论上)更快地获得 GC。

StrongBox含有无糖汽水的所有成分,你有点想多了。您实际上只是加载了 Value一些字段 T稍后再引用。它看起来有点像这样:

var boxedBitmap = new StrongBox<Bitmap>(new Bitmap(1,1));
var bitmap = boxedBitmap.Value;

或者:

var boxedBitmap = new StrongBox<Bitmap>();
boxedBitmap.Value = new Bitmap(1,1);
var bitmap = boxedBitmap.Value;

说真的,如果你在 Reflector 中打开它,这个类的实现就像 5 行。

在这种情况下,您对 ConcurrentQueue<T> 的用法与 ConcurrentQueue<StrongBox<T>> 的用法并没有什么不同.您只需添加 .Value在将资源发送到其目标线程之前。这确实帮助我工作的一家公司通过简单地传递对确定性工具的引用而不是传递整个工具来减少大量多线程分析服务的内存印记,但你的里程可能会有所不同 - 我不清楚如果你传递一些东西来改变然后被其他东西使用,它会产生什么后果。

关于c# - ConcurrentQueue<StrongBox<T>> 的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13612098/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com