【问题标题】:Why the TryPopRange may give exceptions? ConcurrentStack为什么 TryPopRange 可能会出现异常?并发栈
【发布时间】:2020-03-18 13:11:02
【问题描述】:
我在 TryPopRange ConcurrentStack 方法中发现了双重标准。 TryPopRange 方法的名称说,它使用 TryXXX 模式,这不应该给你例外。但是 TryPopRange 方法可以抛出 3 个不同的异常(ArgumentEx、ArgumentNullEx、ArgumentOutOfRangeEx)。好的,检查传入参数是正常的。但是,如果并发堆栈为空,我将有异常。如果一个线程将读取所有数据,而我的线程将使用 TryPopRange 方法,我的读取尝试将只有一个例外。
我可以理解,他们为什么这样做??
【问题讨论】:
标签:
c#
multithreading
concurrent-collections
【解决方案1】:
你指的是TryPopRange这个重载吗?
public int TryPopRange(T[] items, int startIndex, int count);
// Exceptions:
// T:System.ArgumentNullException:
// items is a null reference (Nothing in Visual Basic).
//
// T:System.ArgumentOutOfRangeException:
// startIndex or count is negative. Or startIndex is greater than or equal to the
// length of items.
//
// T:System.ArgumentException:
// startIndex + count is greater than the length of items.
这些异常与ConcurrentStack 集合中的项目数量无关,而是与提供的T[] items 参数的大小有关。您应该将一致的值作为参数传递,因此您不能传递大小为 10 的 items 数组和大小为 11 的 startIndex。